首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >线条组的图例

线条组的图例
EN

Stack Overflow用户
提问于 2010-01-27 01:48:18
回答 5查看 43.2K关注 0票数 20

我喜欢在同一张图上画两组线。每组有两条相同颜色的线条,我必须按一组接一组的顺序绘制它们。我试着只为组显示图例,而不是线。我该怎么做呢?以下是我的错误代码的简化:

代码语言:javascript
复制
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“的东西,但适用于图例。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-01-27 02:15:20

有几种方法可以做到这一点。最简单的方法是获取每个组的第一条绘图线的句柄,并将其作为第一个参数传递给LEGEND

代码语言:javascript
复制
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'});
票数 25
EN

Stack Overflow用户

发布于 2010-01-27 02:27:22

你可以用NaN把多条线缝在一起,意思是“拿起笔”。然后,图例将把每个元素视为一组单独的数据。

代码语言:javascript
复制
hold on
plot([x1 NaN x2], [y1 NaN y2], 'b');
plot([x3 NaN x4], [y3 NaN y4], 'r');
legend({'foo', 'bar'})
hold off

为方便起见,您可以将此代码放在plot的多行版本中。

代码语言:javascript
复制
plot([x1 NaN x2], [y1 NaN y2], 'b', [x3 NaN x4], [y3 NaN y4], 'r');

这也可以让您将分组行的()属性设置为单元。

票数 11
EN

Stack Overflow用户

发布于 2013-04-18 22:02:14

为了响应您的更新,并扩展Andrew Janke的答案,我发现这种方法非常适合自动图例:

代码语言:javascript
复制
% 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‘属性。遵循以下代码以获得与我之前的示例相同的结果:

代码语言:javascript
复制
% 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);

现在,您可以添加任意数量的绘图,图例将自动更新!

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2141403

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档