如何将 2 列图例添加到 Matlab 图中?

How can I add a 2-column legend to a Matlab plot?

考虑以下代码:

t=0:.01:(2*pi);
y=[sin(t);sin(t-pi/12);sin(t-pi/6);sin(t-pi/4)];
figure(1)
    clf
    subplot(6,1,5)
    plot(t,y)
    xlim([0 2*pi])
    legend('1','2','3','4')

生成下图:

有没有办法将图例更改为 2 列布局?所以会是

--- 1 --- 3

--- 2 --- 4

而不是

--- 1

--- 2

--- 3

--- 4

所以图例边界线不会越过图形边界线。

我找到了 gridLegend 脚本,但我更喜欢直接对其进行编码。

您通常可以通过在第一个轴之上制作第二个不可见轴来解决此类问题,如下所示:

t=0:.01:(2*pi);
y=[sin(t);sin(t-pi/12);sin(t-pi/6);sin(t-pi/4)];
figure
subplot(6,1,5)

plot(t,y)
xlim([0 2*pi])
l1 = legend('1', '2');
pos = l1.Position;
set(l1, 'Position', pos - [pos(3) 0 0 0]);
legend boxoff

ax2 = copyobj(gca, gcf);
set(ax2, 'visible', 'off', 'clipping', 'off')
kids = ax2.Children;
set(kids, 'visible', 'off', 'clipping', 'off')
set(ax2, 'children', kids([3:4 1:2]))
l2 = legend(ax2, '3', '4');
legend(ax2, 'boxoff')
legend boxoff

请注意,这很脆弱(例如,无法处理在我的 MATLAB 版本上调整大小的 window)。

MATLAB 从版本 2018a 引入了对图例中多列的原生支持。只需在 legend() 命令末尾添加 'NumColumns',desired_number

在此处查看详细信息 - https://www.mathworks.com/help/matlab/ref/legend.html?lang=en&s_tid=gn_loc_drop#bt6r30y

此外,图例条目的方向可以从上到下更改为从左到右。

By default, the legend orders the items from top to bottom along each column. To order the items from left to right along each row instead, set the Orientation property to 'horizontal'.