# legend in subplot

903 views (last 30 days)
Hassan on 5 May 2011
I am plotting my data using subplot. since the legend is a bit long, I want to put a horzontal legend in top of each two sub plots.I can create a legend for each subplot but don't know how to create one at the top of each two plots. I apperciate your help.
x=1:80;
y=rand(15,80);
j=1;
legend={'LC1','LC2','LC3','LC4','LC5','LC6','LC7'};
for ii=1:4
for i=1:4
subplot(2,2,i)
hold on;
row = 0;
row = row+1;
plot(x(j:j+4),y(row,j:j+4))
end
j=j+5;
end

Hassan on 6 May 2011
I found another way. First I created a subplot with a legend, then placed the legend on the appropriate place on the plot, I created a M-code from the plot and got the position of the legend, then used the position for all subplots. . . .
end
leg1=legend(legend);
set(leg1,'Position',[p1 p2 p3 p4]);
j=j+5;
end
Dan Po on 30 Sep 2016
subplot(121);
peaks
legend('peaks');
subplot(122);
plot(1:10);
legend('1:10')

Adam Danz on 29 Sep 2020
Update
Since this thread continues to get 500+ views per month 9 years later, here's an updated solution for Matlab r2020b or later.
Using TiledLayout, legends can be positioned relative to figure edges and can contain graphics objects from different subplots or tiles.
Examples:

Laura Proctor on 5 May 2011
You cannot have a legend that pulls data from more than one subplot. However, you can plot all the data in one subplot, then set the visibility to off and create a legend that will capture everything. Here's an example:
figure
subplot(211)
plot(1:10)
hold on
hi = plot(sin(1:10),'mx-');
legend('one','two','Location','NorthOutside')
set(hi,'Visible','Off')
subplot(212)
plot(sin(1:10),'mx-');
Hassan on 6 May 2011
all my subplots have the same axis and legend, so I just found the right position for the legend and then used it for all subplots.