在 Matlab 中添加一个矢量作为图例
Add a vector as legends in Matlab
我有一个向量,我想将其条目作为我绘图中图表的标题。我怎么做?我知道我只能在情节中添加 1 个图例。
n=[2 4 6 8 10];
legend(int2str(n));
它应该显示为 5 个不同的图例,分别命名为“2”、“4”......、“10”。
我不太熟悉如何将向量 n 更改为字符串向量。
谢谢
一个简单直观的方法(在我看来)是使用 sprintf
创建与向量的每个元素相对应的字符串。在我的示例中,我使用 for 循环来生成曲线,但如果曲线是在其他地方生成的,这个想法也是一样的。当然,您可以根据需要自定义文本。该代码基于与 n
.
中的元素一样多的曲线
示例:
clear
clc
x = 1:10;
y = rand(1,10);
n=[2 4 6 8 10];
%// Initialize the cell containing the text. For each "n" there is a cell.
LegendString = cell(1,numel(n));
%// Plot every curve and create the corresponding legend text in the loop.
hold all
for k = 1:numel(n)
plot(x,n(k)*y)
LegendString{k} = sprintf('n = %i',n(k));
end
%// Display the legend
legend(LegendString)
输出:
希望这就是您的意思。
对于单行,您可以将 arrayfun
与 num2str
一起使用(感谢@Divakar 的建议):
arrayfun(@(n) ['n = ',num2str(n)],n,'Uni',0)
它给出了一个元胞数组,您可以在调用 legend
.
时直接使用该元胞数组
我有一个向量,我想将其条目作为我绘图中图表的标题。我怎么做?我知道我只能在情节中添加 1 个图例。
n=[2 4 6 8 10];
legend(int2str(n));
它应该显示为 5 个不同的图例,分别命名为“2”、“4”......、“10”。 我不太熟悉如何将向量 n 更改为字符串向量。 谢谢
一个简单直观的方法(在我看来)是使用 sprintf
创建与向量的每个元素相对应的字符串。在我的示例中,我使用 for 循环来生成曲线,但如果曲线是在其他地方生成的,这个想法也是一样的。当然,您可以根据需要自定义文本。该代码基于与 n
.
示例:
clear
clc
x = 1:10;
y = rand(1,10);
n=[2 4 6 8 10];
%// Initialize the cell containing the text. For each "n" there is a cell.
LegendString = cell(1,numel(n));
%// Plot every curve and create the corresponding legend text in the loop.
hold all
for k = 1:numel(n)
plot(x,n(k)*y)
LegendString{k} = sprintf('n = %i',n(k));
end
%// Display the legend
legend(LegendString)
输出:
希望这就是您的意思。
对于单行,您可以将 arrayfun
与 num2str
一起使用(感谢@Divakar 的建议):
arrayfun(@(n) ['n = ',num2str(n)],n,'Uni',0)
它给出了一个元胞数组,您可以在调用 legend
.