present histograms in different colors - matlab

14,620

Solution 1

The h in your code contains the handle to two patch objects. Try to assign a color to each separately:

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

Solution 2

One option is to call hist on both vectors:

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

Another option is to assign the answer to an output argument:

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

And plot them in your favorite style/color.

Solution 3

In the MATLAB standard library, hist uses the command bar to do its plotting, but using bar by itself gives you a lot more flexibility. Passing into bar a matrix whose columns are each histogram's bin counts plots each of those histograms in a different color, which is exactly what you want. Here's some example code:

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

Documentation for bar is here.

Share:
14,620
ariel
Author by

ariel

Updated on June 04, 2022

Comments

  • ariel
    ariel almost 2 years

    I am trying to present two histograms, and I want each of them to be in a different color. lets say one red and one blue. so far I menaged the change the colors of both of them, but only to the same color.
    this is the code

    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.