Legend for multiple data series at once
조회 수: 39 (최근 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!
