Export figure with customized latex legend

4 visualizaciones (últimos 30 días)
Michael Heisel
Michael Heisel el 17 de Oct. de 2021
Respondida: Michael Heisel el 17 de Oct. de 2021
I created a Matlab figure containing a legend with Latex syntax. I also customized the position of the legend labels to make the legend more compact - see example script below.
The code works as intended until I attempt to export the figure, e.g. using "saveas" or "print". Exporting the figure somehow resets the legend interpreter to the default, such that the legend entries look incorrect in the saved figure file.
Is there any way to have the correct legend in the exported figure? I am having this issue with Matlab 2021b on Windows. I was able to export figures like this on a previous version (2017b) with no problem.
% Plot data
x = linspace(0,2*pi);
figure
plot(x,sin(x),x,cos(x))
% Create legend with Latex syntax
[hl,ho] = legend('$10^4$','6\,($10^5$)','Orientation','Horizontal');
set(hl,'box','off','Location','SouthWest')
% Adjust legend label #1
ho(1).Interpreter = 'Latex';
ho(1).Position(1) = ho(1).Position(1)-0.1;
ho(3).XData(2) = ho(3).XData(2)-0.1;
% Adjust legend label #2
ho(2).Interpreter = 'Latex';
ho(2).Position(1) = ho(2).Position(1)-0.3;
ho(5).XData(1) = ho(5).XData(1)-0.2;
ho(5).XData(2) = ho(5).XData(2)-0.3;
Warning: Error updating Legend.

String scalar or character vector must have valid interpreter syntax:
6\,($10^5$)
% Export figure
% Line commented out to see the correct legend labels
% saveas(gcf,'test','epsc')

Respuesta aceptada

Michael Heisel
Michael Heisel el 17 de Oct. de 2021
I found an answer to my own question...
I needed to specify the Latex interpreter as an option in the legend function, rather than in the later lines - see updated code below. It used to be the opposite due to a bug in previous versions (link to bug report). The bug fix may be causing the issue with exporting.
Hopefully this answer helps somebody else.
% Plot data
x = linspace(0,2*pi);
figure
plot(x,sin(x),x,cos(x))
% Create legend with Latex syntax
[hl,ho] = legend('$10^4$','6\,($10^5$)','Orientation','Horizontal','Interpreter','Latex');
set(hl,'box','off','Location','SouthWest')
% Adjust legend label #1
%ho(1).Interpreter = 'Latex';
ho(1).Position(1) = ho(1).Position(1)-0.1;
ho(3).XData(2) = ho(3).XData(2)-0.1;
% Adjust legend label #2
%ho(2).Interpreter = 'Latex';
ho(2).Position(1) = ho(2).Position(1)-0.3;
ho(5).XData(1) = ho(5).XData(1)-0.2;
ho(5).XData(2) = ho(5).XData(2)-0.3;
% Export figure
saveas(gcf,'test','epsc')

Más respuestas (0)

Categorías

Más información sobre Legend en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by