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

Karlo picture Karlo · Jul 25, 2016 · Viewed 9.8k times · Source

Consider following code:

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')

It produces following figure:

![enter image description here

Is there a way to change the legend to a 2-column lay-out? So it would be

--- 1 --- 3

--- 2 --- 4

instead of

--- 1

--- 2

--- 3

--- 4

so the legend boundary lined would not cross the graph boundary lines.

I found the gridLegend script, but I prefer to code it directly.

Answer

ShadowWarrior picture ShadowWarrior · Oct 17, 2018

MATLAB has introduced native support for multiple columns in legend from version 2018a. Just add 'NumColumns',desired_number at the end of the legend() command.

See details here - https://www.mathworks.com/help/matlab/ref/legend.html?lang=en&s_tid=gn_loc_drop#bt6r30y

Additionally, the orientation of the legend entries can be changed from top-to-bottom to left-to-right.

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'.