在循环中创建一个图例

时间:2015-10-01 01:34:49

标签: matlab matlab-figure

我正在尝试使用图例来标记for循环中生成的多个图。我已经阅读了有关此主题的几个Feed。我不确定为什么他们都显得如此不清楚,但我仍然无法想办法让它发挥作用。

x=0:.2:13;
y=zeros(4,length(x));
slope=zeros(1,4);
strings=zeros(1,4);
hold on
grid on

for cnt=1:4

slope(cnt)=-omega(cnt)/trq(cnt);

y(cnt,:)=x*slope(cnt)+omega(cnt);

plot(x,y(cnt,:))

str=sprintf('%f volts',V(cnt));
legend(str)
end

axis([0 .05 0 300])

我试过在循环外移动图例命令,我尝试在循环中创建一个字符串数组。欢迎任何建议。

2 个答案:

答案 0 :(得分:0)

函数adapter.notifyDataSetChanged需要一组字符串,而您目前只在每次调用时传入一个字符串值。因此,您应该在循环中累积所需的字符串作为图例,然后使用该集合在循环外调用legend

legend

答案 1 :(得分:0)

从字符串创建图例的问题是,如果关闭图例然后再将其重新打开,则自定义字符串将消失。因此,我建议设置图形对象的“DisplayName”属性:

x=0:.2:13;
y=zeros(4,length(x));
slope=zeros(1,4);
hold on


for cnt=1:4
slope(cnt)=-omega(cnt)/trq(cnt);
y(cnt,:)=x*slope(cnt)+omega(cnt);

plot(x,y(cnt,:),'DisplayName',sprintf('%f volts',V(cnt)))

end

%# finish the figure
grid on
axis([0 .05 0 300])
legend('show')