如何在 Matlab 中同时显示图块填充和绘图线的图例?

How to display legend for patch fill and plot lines at the same time in Matlab?

我是想给整个剧情赋予传奇色彩。我知道在很多情况下这听起来很容易。但在这个特殊情况下让我感到困惑。

figure;

p1 = plot(1:3,[y1,y2,y3],1:2,y4,1:3,[y5,y6,y7,y8,y9])

% Add lines
hold on
h1 = line([1 2 3],[10 10 10]);
h2 = line([1 2 3],[100 100 100]);
% Set properties of lines
set([h1 h2],'LineStyle','none')
% Add a patch
p2 = patch([1 3 3 1],[10 10 100 100],[.85 .85 .85],'LineStyle','none','FaceAlpha',0.5,'DisplayName','Lab Measurement');
hold off
set(gca, 'children',flipud(get(gca,'children')),'XTickLabel', {'L1' ' ' ' ' ' ' ' ' 'L2' ' ' ' ' ' ' ' ' 'L3'},'YScale', 'log')
NameArray = {'Marker','Color','LineStyle','DisplayName'};
ValueArray = {'o','[0.2 0.2 0.2]','-','Var1';...
    '+','[0.2 0.2 0.2]','-','Var2';...
    '*','[0.2 0.2 0.2]','-','Var3';...
    '.','[0.2 0.2 0.2]','-','Var4';...
    'x','[0.2 0.2 0.2]','-','Var5';...
    's','[0.2 0.2 0.2]','-','Var6';...
    'd','[0.2 0.2 0.2]','-','Var7';...
    '^','[0.2 0.2 0.2]',':','Var8';...
    'h','[0.2 0.2 0.2]','-.','Var9'};
set(p1,NameArray,ValueArray)

当我试图通过给予

来揭示传说时
legend(p1)

legend(p2)

这是我尝试 legend(p2)

时的样子

每个部分都很好,但在一起就不行了。

我也试过在命令中给出图例

legend([p2 p1],{'Lab Measurement','Var1','Var2','Var3','Var4','Var5','Var6','Var7','Var8','Var9'})

legend([p2 p1],{'Lab Measurement',{'Var1','Var2','Var3','Var4','Var5','Var6','Var7','Var8','Var9'}})

没用。任何帮助将不胜感激!

只需使用

p = vertcat(p2,p1);
legend(p)

问题已解决。谢谢!

根据 plot 的文档:

h = plot(___) returns a column vector of chart line objects.

当提供多个绘图对时,如您的情况,plot 中的 return 表示对象数组:

>> a = plot(1, 2, 1, 2)

a = 

  2×1 Line array:

  Line
  Line

拼接的括号表示法[] 一般暗示用户想要创建一个行向量,MATLAB不对向量和标量的情况做假设.这意味着它尝试使用 horzcat 来连接数组,这在逻辑上会引发错误。

>> b = plot(1, 2); c = [a b];

Error using horzcat
Dimensions of matrices being concatenated are not consistent.

您需要明确告诉 MATLAB 您想要将列向量 vertically concatenate these, or transpose 转换为行向量。

>> c = vertcat(a, b)

c = 

  3×1 Line array:

  Line
  Line
  Line

或:

>> c = [a.' b]

c = 

  1×3 Line array:

    Line    Line    Line

两者都兼容legend

赞。