How to add a 2-column legend to the Matlab plot?

Consider the 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 displays the following figure:

! [enter image description here

Is there a way to change the legend to a bar of two columns? So it will be

--- thirteen

--- 2 --- 4

instead

--- one

--- 2

--- 3

--- 4

therefore, the border of the legend’s border does not cross the boundary lines of the graph.

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

+7
graph matlab plot legend legend-properties
source share
1 answer

You can usually hack this thing by making a second invisible axis on top of the first, for example:

 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 (for example, it does not handle window resizing in my version of MATLAB).

+1
source share

All Articles