Legend for multiple data series at once
42 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
David Franco
le 2 Jan 2025
Modifié(e) : Walter Roberson
le 2 Jan 2025
I am plotting 3 datasets (5x100 elements each) directly from the 5x100x3 matrix (I transposed the matrix to get a 100 points x 5 lines plot):
semilogy(matrix(:,:,1)','b.')
hold on
semilogy(matrix(:,:,2)','r.')
semilogy(matrix(:,:,3)','g.')
legend('Data 1','Data 2','Data 3')
When I add the legend, it only shows the same color for each dataset, as it is considering the first 3 rows of the first dataset:

I tried this:
p1 = semilogy(matrix(:,:,1)','b.');
hold on
p2 = semilogy(matrix(:,:,2)','r.');
p3 = semilogy(matrix(:,:,3)','g.');
legend([p1 p2 p3],{'Data 1','Data 2','Data 3'})
But I got the error:
Error using legend
Specify the data series to include in the legend as a vector of graphics objects.
How to add a legend to each 100x5 set?
0 commentaires
Réponse acceptée
Cris LaPierre
le 2 Jan 2025
In MATLAB, each column of data is treated as a series, and by default, each series gets its own legend item. You are plotting 5 series each time, each with the same linespec. Therefore, when you designate 3 legend entries, it grabs the first 3, which all have the same style.
Instead, specify a single handle for each group: legend([p1(1) p2(1) p3(1)],{'Data 1','Data 2','Data 3'})
matrix = rand(3,100,5);
p1 = semilogy(matrix(:,:,1)','b.');
hold on
p2 = semilogy(matrix(:,:,2)','r.');
p3 = semilogy(matrix(:,:,3)','g.');
legend([p1(1) p2(1) p3(1)],{'Data 1','Data 2','Data 3'})
Plus de réponses (0)
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!
