MATLAB Answers

the cyclist

Setting DisplayName for a bar graph

Asked by the cyclist
on 5 Jan 2012

When using the plot() command, one can set the DisplayName property of the plotted lines, and display them in the legend, like so:

hp=plot(1:10,[1:10;2:11]','DisplayName',{'line 1','line 2'});

This approach does not work for a bar graph:

 hb=bar(1:10,[1:10;2:11]','DisplayName',{'line 1','line 2'}); % Error!

I know I can "get" the DisplayName property of the bars, like so:


But is there a way to set the DisplayName property in a vectorized way?

I tried

 set(hb,'DisplayName',{'bar 1','bar 2'})

but the syntax requires a string input there, and balks at the cell array.



1 Answer

Answer by Patrick Kalita
on 5 Jan 2012
 Accepted answer

The help for set says:

set(H,pn,MxN_pv) sets n property values on each of m graphics objects, where m = length(H) and n is equal to the number of property names contained in the cell array pn. This allows you to set a given group of properties to different values on each object.

In this case the length of H is 2 and we're setting 1 property. Therefore the cell array of property names pn will be 1-by-1 and the cell array of property values pv will be 2-by-1:

set( hb, {'DisplayName'}, {'foo'; 'bar'} );
legend show

  1 Comment

Superb. Thank you.

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!