2010-12-16 251 views
3

我想呈现两个直方图,并且我希望它们中的每一个都是不同的颜色。可以说一个红色和一个蓝色。到目前为止,我已经改变了他们两个的颜色,但只改变了相同的颜色。
这是代码不同颜色的直方图-matlab

close all 
b=-10:1:10; 
x=randn(10^5,1); 
x=(x+5)*3; 
y=randn(1,10^5); 
y=(y+2)*3; 
hist(x,100) 
hold on 
hist(y,100); 

h = findobj(gca,'Type','patch'); 
set(h,'FaceColor','r','EdgeColor','w') 
%the last two lines changes the color of both hists. 

回答

3

一种选择是调用hist两个载体:

hist([x(:) y(:)], 100); 

另一种选择是分配的答案输出参数:

[hx, binx] = hist(x, 100); 
[hy, biny] = hist(y, 100); 

而且以最喜欢的风格/颜色绘制它们。

7

代码中的h包含两个修补程序对象的句柄。尝试一种颜色分配给每个单独:

%# ... 
h = findobj(gca, 'Type','patch'); 
set(h(1), 'FaceColor','r', 'EdgeColor','w') 
set(h(2), 'FaceColor','b', 'EdgeColor','w') 
1

在MATLAB标准库,hist使用命令bar做它的绘图,但使用bar本身为您提供了更多的灵活性。传入bar矩阵其列是每个直方图的bin计数以不同颜色绘制每个直方图,这正是您想要的。下面是一些示例代码:

bar
[xcounts,~] = hist(x,100); 
[ycounts,~] = hist(y,100); 
histmat = [reshape(xcounts,100,1) reshape(ycounts,100,1)]; 
bar(histmat, optionalWidthOfEachBarInPixelsForOverlap); 

文档是here