在MATLAB图例中合并线条

时间:2016-06-20 10:05:40

标签: matlab legend

我有两个数据集,我想在同一个图中绘制,例如两个余弦和两个正弦图只是幅度不同:

x = -pi:pi/20:pi;
hold all;
amplitude = 1;
plot(x,amplitude*cos(x),'-');
plot(x,amplitude*sin(x),'-');

ax = gca;
ax.ColorOrderIndex = 1;

amplitude=3;
plot(x,amplitude*cos(x),'.');
plot(x,amplitude*sin(x),'.');

legend('1*cos(x)','1*sin(x)', '2*cos(x)','2*sin(x)');
hold off;

current

我想"压缩"传说使得两条线条(正常线和虚线)是"合并"并显示在图例中相同的文本条目旁边,例如:

desired

如何在MATLAB中实现这一目标?我目前正在使用R2015b。

1 个答案:

答案 0 :(得分:0)

这是我最接近r2015b的快速浏览:

Example image

%%
f = figure;
ax = axes;
x = -pi:pi/20:pi;
hold all;
amplitude = 1;
c1 = plot(x,amplitude*cos(x),'-', 'DisplayName', 'cos(x)');
s1 = plot(x,amplitude*sin(x),'-', 'DisplayName', 'sin(x)');

ax.ColorOrderIndex = 1;

amplitude=3;
c2 = plot(x,amplitude*cos(x),'.', 'DisplayName', ' ');
s2 = plot(x,amplitude*sin(x),'.', 'DisplayName', ' ');

lg = legend([c1 c2 s1 s2]);
hold off;

在HG2之前操作传说更容易 - 所以使用旧版本的Matlab(r2013a)我得到:

enter image description here

%%
f = figure;
ax = handle(axes);
x = -pi:pi/20:pi;
hold all;
amplitude = 1;
c1 = plot(x,amplitude*cos(x),'r-', 'DisplayName', 'cos(x)');
s1 = plot(x,amplitude*sin(x),'b-', 'DisplayName', 'sin(x)');

amplitude=3;
c2 = plot(x,amplitude*cos(x),'r.', 'DisplayName', ' ');
s2 = plot(x,amplitude*sin(x),'b.', 'DisplayName', ' ');

lg = handle(legend([c1 c2 s1 s2]));
hold off;

% You need to find which of the children on the legend is
%  each of the plots:
c1 = handle(lg.Children(1));
c1.YData = 0.3;

s1 = handle(lg.Children(7));
s1.YData = 0.75;