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:
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.
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. Additionally, the orientation of the legend entries can be changed from top-to-bottom to left-to-right.
The function LEGEND allows creation of only one legend object per axes. Multiple legends can be created by using the function COPYOBJ to make a copy of a legend object. The following example illustrates how two legends corresponding to two sets of plots in a figure can be created.
Starting in MATLAB R2014b, legends and colorbars must be associated with an axes. If you want to copy a legend or a colorbar using copyobj, you also must copy the associated axes. A legend must be copied with its associated axes. Use a vector input with COPYOBJ in order to copy the legend and axes together.
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'.
You can usually hack this sort of thing by making a second invisible axis on top of the first, like this:
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
Note that this is fragile (e.g., doesn't handle the window being resized on my version of MATLAB).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With