【问题标题】:creating a legend inside loop在循环内创建图例
【发布时间】:2015-10-01 13:45:25
【问题描述】:

我正在尝试获取一个图例来标记在 for 循环中生成的多个图。我已经阅读了有关此主题的几个提要。我不确定为什么它们看起来都如此不清楚,但我仍然无法找到让它发挥作用的方法。

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

我尝试将图例命令移到循环外,并尝试在循环内创建一个字符串数组。欢迎提出任何建议。

【问题讨论】:

    标签: matlab matlab-figure


    【解决方案1】:

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

    str = cell(1,4); %initialize a cell array to hold the legend strings
    
    for
        .
        .
        .
        str{cnt}=sprintf('%f volts',V(cnt)); %insert text into the appropriate cells
    end
    legend(str)
    

    【讨论】:

      【解决方案2】:

      从字符串创建图例的问题是,如果您关闭图例,然后再将其重新打开,您的自定义字符串就会消失。因此,我建议设置图形对象的 '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')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-02
        • 1970-01-01
        • 2016-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多