G.Hao
G.Hao

Reputation: 11

Matlab bar plot legend

I am try to plot some data into a bar plot and add legend. Matlab assigns four colors to the bars, and I am going to add legend to these colors.

My code is:

data = rand(8, 4);
l = {'a', 'b', 'c', 'd'};
graph = bar(data); 
legend( l );

Matlab can plot the graph, but it cannot add legend. The error message is:

"Error using subsindex
Function 'subsindex' is not defined for values of class 'cell'.
Error in plotDisAndStep
legend( l );"

Upvotes: 1

Views: 1857

Answers (2)

Wasi Ahmad
Wasi Ahmad

Reputation: 37691

You have a comma separated list, so you need to use the following.

legend(l{:});

The problem you are facing can be because of Matlab version you are using. Otherwise your code also should run. For example, your code is working fine in my version (2016) of Matlab.

Upvotes: -1

NLindros
NLindros

Reputation: 1693

Your problem is most probably (as commented TroyHaskin) that you have used legend as variable name earlier in your code. Try to put a clear legend directly above the line with legend( l );. This could be illustrated by this short example

l = {'a', 'b', 'c', 'd'};
A = 1;
A(l)
 Error: Function 'subsindex' is not defined for values of class 'cell'.

Matlab cannot figure out how to convert the cell l to a index.


The legend command works with both comma separeted list and a cell as input with the different labels.

But, using a cell is usually even better as in enables additional name-value pair input arguments without issuing a warning.

Warning: Ignoring extra legend entries.

For example, with your list of labels l (provided that legend isn´t overwritten)

l = {'a', 'b', 'c', 'd'};

You could simply use both

legend(l)    % Cell input
legend(l{:}) % Cell elements fed separately

But using the first you could also add, for example

legend(l, 'FontSize', 8)

Matlab then understand that labels in l are grouped together and the 'FontSize' isn't a label.

If you use

legend(l{:}, 'FontSize', 8);

you will get a warning that the number of lines in the plot (4) don't match the number of legend inputs (since 'FontSize' is also assumed to be a label)

Therefore, you will also be in trouble if your l list is too short and you provide it as an comma separeted list. Then FontSize is included in your legend, see picture below.

data = rand(8, 5);  %  <--   Added one extra line
l = {'a', 'b', 'c', 'd'};
graph = bar(data); 
legend( l{:}, 'FontSize', 8);

Example with bad legend labels

Note that FontSize only is an example of the different name-value pair argument you could use.

Upvotes: 2

Related Questions