Provide a row vector as legend

1 次查看(过去 30 天)
Pedro Oliveira
Pedro Oliveira 2018-1-4
Hi,
I have a bar graph and I'd like to do a legend assigning the values of each column to a specific number which I have stored in a row vector. Since the values of the vector change, instead of writing these myself inside legend(), I'd like to be able to provide the row vector as an input.
Assuming a is my row vector, I tried doing this: legend(a)
But it didn't work.
What can I do?
Thanks in advance for your help.

回答(1 个)

Vedant Shah
Vedant Shah 2025-3-12
To assign the values of a row vector as a legend, each element must be converted into a string. This can be achieved using the num2str function. Additionally, setting 'UniformOutput' to false ensures that the output is returned as a cell array rather than a regular array. For further details, refer to the documentation of the commands:
web(fullfile(docroot, "/matlab/ref/arrayfun.html"))
web(fullfile(docroot, "/matlab/ref/num2str.html"))
The following code snippet demonstrates this approach:
a = [10, 20, 30, 40];
legend_labels = arrayfun(@num2str, a, 'UniformOutput', false);
legend(legend_labels);
Below is the output generated using sample data:

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by