我有两个向量 c 和 d,我需要在 matlab 的同一个图中并排绘制其直方图。当我做 hist(c) 时;坚持,稍等; hist(d) 比例发生变化,我看不到 c 向量的直方图。我哪里错了?任何帮助将不胜感激。
4 回答
If you want the two to be in the same figure, you could try adjusting the X
and Y
limits to suit your needs (try help xlim
and help ylim
). However plotting them in the same figure might not always suit your needs, as a particular plot has to of course maintain a certain limit for X
and Y
.
If displaying them side by side in different figures would suffice however, you could consider using subplot()
:
>> A=[1 1 1 2 2];
>> B=[1 2 2 2 2];
>> figure(1);
>> hold on;
>> subplot(1,2,1);
>> hist(A);
>> subplot(1,2,2);
>> hist(B);
Resultant figure:
Notice how the different axis limits are maintained.
您可以使用axis([xmin xmax ymin ymax])
来控制 x 和 y 轴并选择将显示两个直方图的范围。根据您希望绘图的外观,您可能还想尝试使用nelements = hist(___)
来获取每个 bin 中的元素数量,然后绘制它们bar(x,nelements)
以控制每个条的位置。
我经常使用 MATLAB 直方图,并编写了这个小的 matlab 脚本来在一个图中绘制两个直方图(第一个是红色的,第二个是蓝色的)。该脚本非常简单,但重要的是直方图应该具有可比性(即等间距的频率区间)。
function myhist(varargin)
% myhist function to plot the histograms of x1 and x2 in a single figure.
% This function uses the same xvalue range and same bins to plot the
% histograms, which makes comparison possible.
if nargin<2
x1 = cell2mat(varargin(1));
x2 = x1;
res = 100;
elseif nargin==2
x1 = cell2mat(varargin(1));
if length(cell2mat(varargin(2)))==1
res = cell2mat(varargin(2));
x2 = x1;
else
x2 = cell2mat(varargin(2));
res = 100;
end
elseif nargin>2
x1 = cell2mat(varargin(1));
x2 = cell2mat(varargin(2));
res = cell2mat(varargin(3));
end
if numel(x1)~=length(x1) || numel(x2)~=length(x2)
error('Inputs must be vectors.')
return
end
xrangel = max(min(x1),min(x2));
xrangeh = min(max(x1),max(x2));
x1_tmp = x1(x1>=xrangel & x1<=xrangeh);
x2_tmp = x2(x2>=xrangel & x2<=xrangeh);
xbins = xrangel:(xrangeh - xrangel)/res:xrangeh;
hist(x1_tmp,xbins)
hold on
h = findobj(gca,'Type','patch');
set(h,'FaceColor','r','EdgeColor','w');
hist(x2_tmp,xbins)
hist
假设您希望默认将范围划分为 10 个大小相等的 bin。如果您想对两个直方图使用相同的 bin,首先找到您的值的范围并制作一组 bin 中心(例如binCenters = linspace(min(x), max(x), 15)'), then call
hist(x, binCenters)`。