Why does my legend only display 50 entries?

조회 수: 73 (최근 30일)
MathWorks Support Team
MathWorks Support Team 2017년 10월 20일
댓글: Walter Roberson 2020년 12월 24일
I have a plot with more than 50 items and I would like to add a legend for all of them. The legend gets truncated at 50.
p = plot(magic(100));
labels = cellstr(num2str((1:100)'));
legend(p,labels)
 

채택된 답변

MathWorks Support Team
MathWorks Support Team 2017년 10월 20일
Legends are currently limited to no more than 50 entries. Usually in plots with more than 50 features, the plot is so cluttered and the legend is so large that it is more advisable to select just a few key items to display in the legend.
If you do require more than 50 entries, the workaround is to create an additional legend. This requires creating an additional hidden axes.
First plot the original data.
p = plot(magic(100));
labels = cellstr(num2str((1:100)'));
legend(p(1:50),labels(1:50),'location','westoutside')
Next create an additional axes so that the figure can have two legends. Because the new legend needs information about the color of each line, it is necessary to copy the original lines to this new axes.
set(gcf,'NextPlot','add')
newAx = axes;
newP = copyobj(p,newAx);
legend(newP(51:100),labels(51:100),'location','eastoutside')
Now make the new axes and copied lines invisible. Normally, this would be done by setting the Visible property of each line to 'off', however this would gray out the corresponding entries in the legend. Instead, set the XData and YData properties of each line to NaN.
axis(newAx,'off')
set(newP,'XData',NaN,'YData',NaN)
  댓글 수: 1
Eric Sargent
Eric Sargent 2020년 12월 9일
Legend will cap the number of entries at 50 if no handles are specified. To have all objects in an axes show up, pass in their handles to the legend command.
p = plot(magic(100));
legend(p);

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Eric Sargent
Eric Sargent 2020년 12월 9일
Legend will cap the number of entries at 50 if no handles are specified. To have all objects in an axes show up, pass in their handles to the legend command.
p = plot(magic(100));
legend(p);
  댓글 수: 1
Walter Roberson
Walter Roberson 2020년 12월 24일
It gets the axes handles from ancestor(p, 'axes') so it does not need to be passed a handle axes.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

제품


릴리스

R2017a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by