legend in subplot
    174 vues (au cours des 30 derniers jours)
  
       Afficher commentaires plus anciens
    
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
0 commentaires
Réponse acceptée
  Hassan
 le 6 Mai 2011
        2 commentaires
  Simon Mwakitabu
 le 16 Jan 2024
				This results to individual legend on each subplot. Not a common one on top of the figure including all plots.
New versions of Matlab since 2019 has tiled_layout with incredible features.
Plus de réponses (2)
  Adam Danz
    
      
 le 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:
0 commentaires
  Laura Proctor
    
 le 5 Mai 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-');
6 commentaires
  Johanna
 le 6 Sep 2023
				
      Modifié(e) : Adam Danz
    
      
 le 6 Sep 2023
  
			If I use the solution proposed by Laura Proctor, the word "two" in the legend is somewhat transparent even if I try to force it to be black. Any ideas?
figure
subplot(211)
plot(1:10)
hold on
hi = plot(sin(1:10),'mx-');
h_legend= legend('one','two','Location','NorthOutside')
set(h_legend,'TextColor','k')
set(hi,'Visible','Off')
subplot(212)
plot(sin(1:10),'mx-');
  Adam Danz
    
      
 le 6 Sep 2023
				It's because of this line
set(hi,'Visible','Off')
You are setting the 2nd line in the first axes to Visible=off so it is not displayed.  Therefore, it's grayed out in the legend. 
Instead, use object handles to specify what should go in the legend. 
Voir également
Catégories
				En savoir plus sur Legend dans Help Center et File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!






