简体   繁体   中英

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

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

带有错误图例标签的示例

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM