Provide a row vector as legend

1 回表示 (過去 30 日間)
Pedro Oliveira
Pedro Oliveira 2018 年 1 月 4 日
回答済み: Vedant Shah 2025 年 3 月 12 日
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 Center および File ExchangeLegend についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by