How do I make a figure legend multiple lines?

1.154 visualizaciones (últimos 30 días)
The string for my legend is too long to fit into one line. I would like to split it into multiple lines.

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 9 de Jun. de 2020
Editada: MathWorks Support Team el 23 de Nov. de 2020
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.

Más respuestas (2)

Christoforos Kanavakis
Christoforos Kanavakis el 23 de Mzo. de 2018
In newer versions, Matlab recommends using 'newline'.
So,
legend({['blue' newline 'line'],'red line'})

Sulaymon Eshkabilov
Sulaymon Eshkabilov el 18 de Mayo de 2022
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

Etiquetas

Aún no se han introducido etiquetas.

Productos


Versión

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by