Legend in a bar plot in Matlab

删除回忆录丶 提交于 2019-12-04 08:46:09

问题


How can I plot a legend in a bar plot in Matlab? Here is the code:

Y = [1.5056
0.72983
3.4530
3.2900
1.4839
12.9 ];
n = length(Y);
h = bar(Y);
colormap(summer(n));
grid on

l = cell(1,6);
l{1}='L'; l{2}='B'; l{3}='R'; l{4}='P'; l{5}='h'; l{6}='Ri';    
legend(h,l);

This give an error: Warning: Ignoring extra legend entries. I tried solutions which I found on the SO and web, but I couldn't resolve this.


回答1:


Instead of legend, you can solve it using the tick labels for example:

set(gca,'xticklabel', l) 

This will label each bar. If you want to use legend you need to have a matrix data, so the bar plot will show several bars per entry. For example

Y=rand(10,6)
h = bar(Y);
colormap(summer(n));
grid on
l = cell(1,6);
l{1}='L'; l{2}='B'; l{3}='R'; l{4}='P'; l{5}='h'; l{6}='Ri';    
legend(h,l);

Or, you can use different bar() calls in this way:

h = bar(diag(Y));

But then you'll get a displacement per each bar:

So, the only way really to do that using legend is to plot each bar seperatly, similar to what is discussed here.




回答2:


Further to bla's answer, you can use

h = bar(diag(Y),'stacked');

if you want to avoid the displacement.



来源:https://stackoverflow.com/questions/14697525/legend-in-a-bar-plot-in-matlab

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