Search code examples
plotoctavelegendfigureaxis-labels

Using LaTeX in legends and labels of plots?


I'm trying to add a legend with the function being drawn on the plot, e.g.:

description = legend({"y(x) = \sqrt{\frac{100(1-0.10x^2)^2+0.02x^2}{(1-x^2)^2+0.1x^2}}"});

legend(description ,"location", "northoutside");

however, the result I get is:

enter image description here

What is the correct syntax to include LaTeX math mode symbols?


Octave-4.2.1 on Windows 10


Solution

  • I can confirm that this works in matlab:

    p = plot(1:10);
    description = '$y(x) = \sqrt{\frac{100(1-0.10x^2)^2+0.02x^2}{(1-x^2)^2+0.1x^2}}$';
    l = legend(description);
    set(l, 'interpreter', 'latex');
    

    but not in octave.

    So presumably the issue Andy mentioned in the linked post, still holds.

    I know this isn't ideal, but as a workaround, I would simply import a pre-rendered latex image in its own axes, and manually place it on top of your main plot's axes. I find the fastest way to generate latex text / equation snippets is with anki.

    For instance, I generated this with anki:

    Then in octave I might do:

    PlotAxes = axes();
    plot(1:10, 'g');
    set (PlotAxes, 'position', [0.1, 0.1, 0.8, 0.7]);
    
    LegendAxes = axes();
    [LegendText, Colourmap] = imread('https://i.sstatic.net/dOOnQ.png');
    LegendText = ind2rgb (LegendText, Colourmap);
    imagesc(LegendText);
    axis equal tight;
    Lims = axis;
    hold on;
    LegendLine = plot ([-150, -50], [50, 50], 'linewidth', 3, 'g');
    hold off;
    axis(Lims + [-200, 0, 0, 0]);
    set (LegendAxes, ...
       'position', [0.2, 0.85, 0.6, 0.1], ...
       'xtick', [], 'ytick', [], 'box', 'on');
    

    Result:

    Manual placement of this sort might seem like a very cumbersome thing to do at first, but once you get used to it, I guarantee you will actually prefer it. All the figures in my thesis were 'manually' positioned (though often in an automated manner) since this allowed me complete control.