How do I make a figure legend multiple lines?

조회 수: 1,071 (최근 30일)
MathWorks Support Team
MathWorks Support Team 2011년 1월 13일
답변: Sulaymon Eshkabilov 2022년 5월 18일
The string for my legend is too long to fit into one line. I would like to split it into multiple lines.

채택된 답변

MathWorks Support Team
MathWorks Support Team 2020년 6월 9일
편집: MathWorks Support Team 2020년 11월 23일
To split legend to multiple lines, use the "newline" function or the ASCII character 10 for new line, for example:
>> plot(sin(1:10),'b')
>> hold on
>> plot(cos(1:10),'r')
>> legend({['blue' char(10) 'line'],'red line'})
With MATLAB "strings" you can use the following notation:
>> legend({ "blue" + newline + "line", 'red line'})
or
>> legend({ strcat("blue", string(newline), "line"), 'red line' })
In addition to the MATLAB command line, the legend can also be updated interactively in the figure itself to include multi-line legend entries.

추가 답변 (2개)

Christoforos Kanavakis
Christoforos Kanavakis 2018년 3월 23일
In newer versions, Matlab recommends using 'newline'.
So,
legend({['blue' newline 'line'],'red line'})

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2022년 5월 18일
This one is a better solution that is easier to implement:
plot(sin(1:.1:10),'r', 'DisplayName', 'Cosine'), hold on
plot(cos(1:.1:10),'g', 'DisplayName', 'Sine')
plot(tan(1:.1:10),'b', 'DisplayName', 'Tangent')
plot(1./tan(1:.1:10),'k', 'DisplayName', 'Inverse Tangent'), grid on
My_LGD = legend;
My_LGD.NumColumns = 2; % Show legends in two lines

카테고리

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

태그

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

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by