我喜欢在同一张图上画两组线。每组有两条相同颜色的线条,我必须按一组接一组的顺序绘制它们。我试着只为组显示图例,而不是线。我该怎么做呢?以下是我的错误代码的简化:
plot(x1, y1, color1); hold on;
plot(x2, y2, color1); hold on;
plot(x3, y3, color2); hold on;
plot(x4, y4, color2); hold on;
legend({color1, color2})
谢谢!
更新:
一个新的问题是,有没有办法在每一行之后写入图例,而不覆盖之前的图例并附加到它上面?即类似于"hold on“的东西,但适用于图例。
发布于 2010-01-27 02:15:20
有几种方法可以做到这一点。最简单的方法是获取每个组的第一条绘图线的句柄,并将其作为第一个参数传递给LEGEND
h1 = plot(x1, y1, color1);
hold on;
plot(x2, y2, color1);
h2 = plot(x3, y3, color2);
plot(x4, y4, color2);
legend([h1 h2],{'label1', 'label2'});
发布于 2010-01-27 02:27:22
你可以用NaN把多条线缝在一起,意思是“拿起笔”。然后,图例将把每个元素视为一组单独的数据。
hold on
plot([x1 NaN x2], [y1 NaN y2], 'b');
plot([x3 NaN x4], [y3 NaN y4], 'r');
legend({'foo', 'bar'})
hold off
为方便起见,您可以将此代码放在plot的多行版本中。
plot([x1 NaN x2], [y1 NaN y2], 'b', [x3 NaN x4], [y3 NaN y4], 'r');
这也可以让您将分组行的()属性设置为单元。
发布于 2013-04-18 22:02:14
为了响应您的更新,并扩展Andrew Janke的答案,我发现这种方法非常适合自动图例:
% Sample data
order = -1:2; % number of orders to plot
x = (0:0.01:10)';
% Plot each instance of data in a separate graph
for i=1:numel(order)
plot(x,besselj(order(i),x))
hold all
% Amend legend to include new plot
[~,~,~,current_entries] = legend;
legend([current_entries {sprintf('Order = %i',order(i))}]);
end
如下图所示:
编辑:在Matlab 2014b中,"legend“的用法已经改变,上面的解决方案将抛出错误。相反,我们应该修改图例的'String‘属性。遵循以下代码以获得与我之前的示例相同的结果:
% Sample data
order = -1:2; % number of orders to plot
x = (0:0.01:10)';
% Plot each instance of data in a separate graph
for i=1:numel(order)
plot(x,besselj(order(i),x))
hold on
% Amend legend 'entries' to include new plot
entries(i) = { sprintf('Order = %i',order(i)) };
end
% Create legend using the 'entries' strings
legend('String',entries);
现在,您可以添加任意数量的绘图,图例将自动更新!
https://stackoverflow.com/questions/2141403
复制相似问题