我想在图例中添加一个红色十字和一个青色点(我不希望该行在图例中)但是这会在图例中添加直线和红色十字。我怎么能删除那条线,那里只有一个红叉和蓝点?
x = -1:0.01:1;
y = @(x) x.^2;
hold on
plot(x, y(x), '.-')
for x = -1:0.01:1;
if (x < 0)
plot(x, y(x), 'rx');
else
plot(x, y(x), 'c.');
end
end
hold off
legend('red cross', 'cyan dot')
产生数字
答案 0 :(得分:1)
您可以通过将其句柄指定为legend
函数的输入来指定必须在图例中显示哪组数据。
您必须按如下方式修改代码:
x = -1:0.01:1;
y = @(x) x.^2;
hold on
p1=plot(x, y(x), '.-')
for x = -1:0.01:1;
if (x < 0)
p2=plot(x, y(x), 'rx');
else
p3=plot(x, y(x), 'c.');
end
end
hold off
legend([p2 p3],'red cross', 'cyan dot')
即:使用if
部分获取两个图的句柄(仅绘制十字和星标的图,然后在legend
的调用中指定它们。
通过这样做,第一个图(plot(x, y(x), '.-')
)的图例不会显示。
希望这有帮助。
答案 1 :(得分:0)
您可以根据here说明执行此操作。但总的来说,它缩减为此命令,其中h
是要从图例中删除的图形对象的句柄。
set(get(get(h1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off')
因此,对于您的代码,它看起来像这样:
x = -1:0.01:1;
y = @(x) x.^2;
hold on
h1 = plot(x, y(x), '.-')
for x = -1:0.01:1;
if (x < 0)
h2 = plot(x, y(x), 'rx');
else
h3 = plot(x, y(x), 'c.');
end
end
set(get(get(h1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off')
hold off
legend('red cross', 'cyan dot')