Legend for multiple data series at once
17 ビュー (過去 30 日間)
古いコメントを表示
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1822491/image.png)
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 件のコメント
採用された回答
Cris LaPierre
2025 年 1 月 2 日
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'})
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Legend についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!