【问题标题】:Legend containing only specific plots仅包含特定地块的图例
【发布时间】:2014-03-18 00:17:46
【问题描述】:

我在一个图中有 10 条曲线,但其中只有 3 条应该出现在图例中。例如,10条曲线中,只有第一条、第五条和第十条应该在图例中,我该怎么做?

这是我的程序:

x=1:0.5:15;
y1=x.^1
plot(x,y1)
hold on
y2=x.^1.2
plot(x,y2)
hold on
.
.
.
y10=x.^2.2
plot(x,y10)

【问题讨论】:

  • 你是说子情节? 10 个合一?

标签: matlab matlab-figure legend


【解决方案1】:

您可以使用图例的句柄,然后通过图例的句柄指定图例:

x=1:0.5:15;
y(1,:)=x.^1;
y(2,:)=x.^1.2;
...
...
...
y(10,:)=x.^2.2;

for k=1:10
   h(k)=plot(x,y(k,:));
   hold on
end
legend([h(1) h(5) h(10)],'curve 1','curve 5','curve 10');
hold off

【讨论】:

    【解决方案2】:

    legend 可以接受一个或多个句柄,以及一个字符串列表。我冒昧地重写了您的代码,因此它绘制在一个循环中,而不是创建一堆y 变量。一般来说,如果您发现自己创建了一系列名为 y1、y2 等的变量,那么在 MATLAB 中有一种更好的方法。

    有 7 个地块,而不是 10 个,但你明白了。

    x=1:0.5:15;
    m=1:0.2:2.2; 
    
    figure
    hold on
    
    for n = 1:7
       h(n) = plot(x,x.^m(n));
    end
    
    legend(h([1,3,5]),'Plot One', 'Plot Three', 'Plot Five',...
    'Location', 'NorthWest')
    

    【讨论】:

      【解决方案3】:

      您需要使用图例函数中的绘图句柄来指示所需的曲线。插入到您的代码中,它看起来像这样:

      x=1:0.5:15;
      y1=x.^1;
      h1=plot(x,y1,'r');
      hold on
      y2=x.^1.2;
      h2=plot(x,y2,'c');
      hold on
      .
      .
      .
      y10=x.^2.2;
      h10=plot(x,y10,'p');
      
      
      hold off;
      
      legend([h2,h10] , 'Fart 2', 'More Fart');  % Plot in the handle you wish
      

      【讨论】:

      • 一个hold on 就足够了。此外,hold all 将自动循环通过 ColorOrder
      • 是的,当然,我忘了从他的代码中删除它们。 +1 hold all 技巧,SA 让我的生活更轻松了一步。
      【解决方案4】:

      这是我使用的光滑的两线:

      a=flipud(findall(gcf,'Type','Line')); %get all line objects of current plot
      legend(a([1 3]),{'a','b'}) %add legend for line 1 and 3, 'a' and 'b'
      

      【讨论】:

        【解决方案5】:

        legend 命令仅适用于最近创建的绘图,除非传递了句柄。

        figure
        for c=1:10
            subplot(4,4,c)
            ezplot('y=sin(x)');
            if c==5||c==10
                legend('sin(x)')
            end
        end
        

        【讨论】:

        • 抱歉,我的图中有 10 条曲线
        猜你喜欢
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-31
        • 2018-11-25
        • 1970-01-01
        • 2012-12-26
        • 2013-12-01
        相关资源
        最近更新 更多