Search code examples
matlabpdflatexmatlab-figurelegend

Why is Matlab placing text spaces in legend using Latex when the figure gets saved as a PDF?


I am trying to put a legend in Matlab figures that include a symbol in Latex. When I plot the figure, the legend looks fine. However, when I export the figure as a PDF, the legend gets spaces put into it. I don't know why this is happening. Sample code is as follows:

set(groot,'defaultLineLineWidth',2,'defaultAxesFontSize',...
    12,'defaultAxesFontName','timesnewroman',...
    'defaulttextinterpreter','latex')
x0 = 8;
y0 = 5;
width = 5;
height = 4;
kappa1 = 0.1;
kappa2 = 0.5;
f = linspace(0,2*pi,1000);
y1 = sin(f+kappa1*f.^2);
y2 = sin(f+kappa2*f.^2);

figure(1)
hold on
plot(f,y1,'k')
plot(f,y2,'b')
xlabel('Frequency (MHz)')
ylabel('Amplitude')
legend(strcat('\kappa = 0.1 MHz/','\mu','s'),...
    strcat('\kappa = 0.5 MHz/','\mu','s'))
grid on;
set(gcf,'units','inches','Position',[x0,y0,width,height],...
    'PaperPositionMode','Auto','PaperUnits','Inches',...
    'PaperSize',[width, height]);
saveas(gcf,'legendtest.pdf')

It seems like the error happens when I save the file as a PDF. It saves as a JPG just fine. Below are the two images I get. The jpg is:

testlegendjpg

But the PDF I get is:

enter image description here

I am using Matlab version R2017a on a Mac running OS 10.12.5. Thanks in advance for any help!


Solution

  • Another workaround is to just interpret the whole legend text with Latex:

    h = legend(strcat('$\kappa$ = 0.1 MHz/','$\mu$','s'),...
        strcat('$\kappa$ = 0.5 MHz/','$\mu$','s'))
    set(h,'Interpreter','latex')
    

    It requires some basic Latex knowledge, e.g. you have to wrap all math signs (kappa, mu) with $ and beware if you want to use any special non-english characters. Changes the look of the legend a bit, but arguably for the better.

    Btw, you can skip strcat, it does not serve any purpose.

    h = legend('$\kappa$ = 0.1 MHz/$\mu$s',...
        '$\kappa$ = 0.5 MHz/$\mu$s')
    set(h,'Interpreter','latex')
    

    Works just as well, the same goes for the non latex version.