Question

I have a legend with 7 entries, some of which are on one subplot, some are on another, and some are common to both plots. I have managed to get all of these entries into one legend using some help I found online, which was great.

Only problem I have now is that the strings for each entry are quite long, so I ideally need them in 2 columns with the 7th entry centred in the middle at the bottom of the legend. I have found various options to do a multi-columned legend:

But I can't work out how to combine them with the way I have already worked out how to do the legend.

This is MWE of what I have so far:

xdata=1:1:10;
ydata=0:0.1:0.9;
% Line colours
cm=[32 114 214;145 205 237;0 129 63;247 217 9;255 127 0;184 18 21];
cm=cm/255;   
h1=subplot(2,1,1);
l1=line(xdata,ydata,'Color',cm(1,:));
l2=line(xdata,ydata,'Color',cm(2,:));
l3=line(xdata,ydata,'Color',cm(3,:));
l5=line(xdata,ydata,'Color',cm(5,:));
l7=line(xdata,ydata,'Color','k','LineStyle','--');
h2=subplot(2,1,2);
l4=line(xdata,ydata,'Color',cm(4,:));
l6=line(xdata,ydata,'Color',cm(6,:));
line(xdata,ydata,'Color','k','LineStyle','--');
hL=legend(h2,[l1,l2,l3,l4,l5,l6,l7],{'Second/Multi-year La Niña','First/Single-year La    Niña','Neutral ENSO years','First/Single-year El Niño','El Niño years','Second/Multi-year El Niño','All Years (1901-2011)'},'Location','SouthOutside','Orientation','horizontal');
set(hL,'Units','centimeters');
Lpos=get(hL,'Position');
Lpos(1)=0;
Lpos(2)=0;
set(hL,'Position',Lpos);

My actual data doesn't overlap so you can see all the lines. Was just easier to have it like that for the example.

Can anyone help me out with the layout I need for the legend? It may well be that I can use one of the 3 options I already found, but I don't really understand what they do well enough to apply it to my situation.

Was it helpful?

Solution

I found another work around with this, which is to create 3 separate legends and then position them where I want. I made a 3rd subplot which has the 'Visible','off' setting and called my three legends using the following code:

lg1=legend(h1,[l1,l2,l3],{'a','b','c'});
lg2=legend(h2,[l4,l5,l6],{'d','e','f'});
lg3=legend(h3,l7,{'g'});

where h1-3 are the subplots, l1-7 are the 7 lines, and a-g are the legend text. I have then rearranged them using get(lg1,'Position'), changing the position vector, and resetting it using set(lg1,'Position',...) (replace ... with the position vector). I turned the box off around the three legends, but plan on putting a box all round the edge so it looks like it is one legend.

Not the prettiest way to do it, but it worked for what I needed to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top