Wrong legends when plotting histogram with `hold on`

本小妞迷上赌 提交于 2020-01-05 09:05:31

问题


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.



来源:https://stackoverflow.com/questions/9217777/wrong-legends-when-plotting-histogram-with-hold-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!