使用“hold on”绘制直方图时错误的图例

时间:2012-02-09 19:55:44

标签: matlab plot histogram legend

我在子图上绘制直方图,每个图有两个直方图,如下图子部分所示:

enter image description here

问题:我希望带有名为result_uT_per_window的变量的hist具有红色图例,而希望带有名为uT_top_of_global_window的变量的hist具有蓝色图例。我认为我在代码中拥有的东西应该这样做,但事实并非如此。这是代码:

    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')

你能注意到我哪里出错吗?感谢。

1 个答案:

答案 0 :(得分:2)

假设h(1)是您的第一个hist命令生成的内容时出错:

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

产生

enter image description here

显示data1(平均值为10)以蓝色绘制,证明其句柄为h(2),即使它是先绘制的。

因此,要解决您的问题,您可以写

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

按照您期望的顺序显示h中的句柄。