Wrong legends when plotting histogram with `hold o

2019-08-14 18:48发布

问题:

I am plotting histograms on a subplot, where each plot has two histograms as shown in one part of the subplot below:

Question: I would want the hist with variable named result_uT_per_window to have red legend, and hist with variable named uT_top_of_global_window to have blue legend. I thought what I have in code is supposed to do that, but it doesn't. This is the code:

    hold on
    hist(nonzeros(result_uT_per_window(:,window_no)))
    hist(uT_top_of_global_window)
    h = findobj(gca, 'Type','patch');
    set(h(1), 'FaceColor','r', 'EdgeColor','w')
    set(h(2), 'FaceColor','b', 'EdgeColor','w')
    xlabel('Total Velocity (in m/s)')
    ylabel('Frequency')
    legend('From moving window','From global window')

Can you notice where am I going wrong? Thanks.

回答1:

You go wrong in assuming that h(1) is what was produced by your first hist command:

data1=normrnd(10,1,10000,1);
data2=normrnd(20,1,10000,1);
figure;
hold on;
hist(data1);
hist(data2);
h = findobj(gca, 'Type','patch');
set(h(1), 'FaceColor','r', 'EdgeColor','w') % color h1 plot red
set(h(2), 'FaceColor','b', 'EdgeColor','w') % color h2 plot blue

produces

showing that data1 (with mean value 10) is plotted in blue, proving that its handle is h(2) even though it was plotted first.

Hence, to solve your problem you could write

h = flipud(findobj(gca, 'Type','patch'));

to bring the handles in h in the order that you expect.