Legend for multiple data series at once
8 次查看(过去 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:

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!