Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Legend in a bar plot in Matlab

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.

like image 241
Makaroni Avatar asked Feb 04 '13 23:02

Makaroni


People also ask

How do I add a legend to a bar graph in MATLAB?

Specify Labels Using DisplayName Alternatively, you can specify the legend labels using the DisplayName property. Set the DisplayName property as a name-value pair when calling the plotting functions. Then, call the legend command to create the legend. Legends automatically update when you add or delete a data series.

How do you plot a legend position in MATLAB?

legend(___,'Location', lcn ) sets the legend location. For example, 'Location','northeast' positions the legend in the upper right corner of the axes. Specify the location after other input arguments. legend(___,'Orientation', ornt ) , where ornt is 'horizontal' , displays the legend items side-by-side.

How do you add a legend title in MATLAB?

To add a legend title, set the String property of the legend text object. To change the title appearance, such as the font style or color, set legend text properties. For a list, see Text Properties. plot(rand(3)); lgd = legend('line 1','line 2','line 3'); lgd.


1 Answers

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

set(gca,'xticklabel', l) 

enter image description here

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

enter image description here

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

h = bar(diag(Y));

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

enter image description here

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

like image 139
bla Avatar answered Sep 26 '22 13:09

bla