Adding legend for subplot when none of the subplots include all legend entries
Show older comments
Hi folks, I am trying to create a subplot where the points are coloured by year, and the years have the same colour in each subplot. Through careful control of the colours I have been able to achieve this, but I only want one legend for the figure, and none of the subplots contain all the years. I cannot figure out (excuse the pun!) how to create just one legend that has all the years (2011-2016). I can easily position one legend at the bottom of the subplot, that's not the problem. Here is the code to make the figure with individual legends (which I don't want in the end) to show you what I mean, along with the code. Thank you!
st_colours=[0, 0.4470, 0.7410;0.8500, 0.3250, 0.0980; 0.9290, 0.6940, 0.1250; 0.4940, 0.1840, 0.5560; 0.4660, 0.6740, 0.1880; 0.3010, 0.7450, 0.9330; 0.6350, 0.0780, 0.1840];
figure15 = figure();
for m=1:12
subplot(4,3,m)
if m==1 || m==2 || m==3 || m==4 || m==5 || m==6 || m==8 || m==11 || m==12 %Month
for r=1:5 %The row this time
sc(m,r)=scatter(QQG_Amm3M_T_split(m).months.NOAA_ONI(r),QQG_Amm3M_T_split(m).months.mean_Tmelt(r),25,'filled');hold on;
end
end
if m==7 || m==9 || m==10
for r=1:4 %The row this time
sc(m,r)=scatter(QQG_Amm3M_T_split(m).months.NOAA_ONI(r),QQG_Amm3M_T_split(m).months.mean_Tmelt(r),25,'filled');hold on;
end
end
if m==11 || m==12
for r=1:5 %The row this time
sc(m,r).MarkerFaceColor=st_colours(r,:);
end
elseif m==1 || m==2 || m==3 || m==4 || m==5 || m==6 || m==8
for r=1:5 %The row this time
sc(m,r).MarkerFaceColor=st_colours(r+1,:);
end
else
for r=1:4 %The row this time
sc(m,r).MarkerFaceColor=st_colours(r+1,:);
end
end
legend(string(QQG_Amm3M_T_split(m).months.mean_Year));
title(Month_labels(m));
xlim([-2 2.5]);
ylim([0 1]);
end

Accepted Answer
More Answers (1)
Mario Malic
on 29 Sep 2020
Legend command is in the loop, therefore it is generated for each subplot. If you want to have it on particular month, you can put this within condition
if m == 1 % Jan
legend(string(QQG_Amm3M_T_split(m).months.mean_Year));
end
Or you can put it just outside of loop, and legend will be on December.
5 Comments
Catriona
on 29 Sep 2020
Walter Roberson
on 29 Sep 2020
There is a legend for each axes (and subplots are axes). There is no direct method for creating an overall legend for a collection of axes.
Catriona
on 29 Sep 2020
Mario Malic
on 29 Sep 2020
Having an additional scatter command for the January, you can have enough entries in the legend, and for it make the legend, but it's not a proper solution.
scatter(nan, nan);
Or maybe you could add an entry to your structure (nan, nan) to December and adjust the code, as it's easier to append the last value rather than the first.
Catriona
on 29 Sep 2020
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
