Export figure with customized latex legend

4 views (last 30 days)
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')

Accepted Answer

Michael Heisel
Michael Heisel on 17 Oct 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')

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!