Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 253
Ziezi Avatar asked Oct 23 '25 04:10

Ziezi


2 Answers

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.

like image 157
Tasos Papastylianou Avatar answered Oct 27 '25 02:10

Tasos Papastylianou


Depending on the variety of TeX math symbols you use, it may suffice using quoting with '' instead of "".

For instance,

  1. Powers work well with any of the two.
  2. '\rho' gets the correct legend, while "\rho" does not. Likewise for other greek symbols I tested.
  3. \frac and \sqrt work with none of the two.

I did not look for authoritative information with more details, and you are in case 3, so using single quotes is not enough. But it may be enough for others (as it was for me).

like image 41
sancho.s ReinstateMonicaCellio Avatar answered Oct 27 '25 00:10

sancho.s ReinstateMonicaCellio