Ask Your Question

Latex in plot()/text() - include extra latex packages

asked 2018-09-20 05:18:56 -0500

MartinS gravatar image


I'm desperately trying to label axes using the siunitx package, for example:

plot(..., axes_labels=['$\si{\volt}$', '\si{\second}'])
text("\SI{1}{\ampere}", (2, 2))

However, I cannot find a way how to load the package. So far I have tried:

from matplotlib import rc
rc('text', usetex=True)
rc('text.latex', preamble='\\usepackage{siunitx}')


from sage.misc.latex import latex_extra_preamble

Neither of these seems to work (\SI is either simply ignored or unknow). Furthermore, I need to use the '\text{}' macro, which seems to be unavailable as well (need to load amsmath?).

Any help most appreciated!

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2018-09-22 08:57:10 -0500

eric_g gravatar image

First of all, you should enter all strings containing some LaTeX code with the prefix r (for "raw" string), so that the backslash character is correctly interpreted as part of a LaTeX command. For instance, you should write

plot(..., axes_labels=[r'$\si{\volt}$', r'$\si{\second}$'])

Another option would be to double all backslashes:

plot(..., axes_labels=['$\\si{\\volt}$', '$\\si{\\second}$'])

Unfortunately, the import of the siunitx package does not work in SageMath 8.3. This bug has been fixed in the ticket #25799. Since this ticket has been merged in SageMath 8.4.beta0, everything will be OK with SageMath 8.4. I've just checked that with SageMath 8.4.beta4, after having installed the system (Ubuntu in my case) packages texlive-science (which provides siunitx) and dvipng (required by Matplotlib to process LaTeX texts) the following works:

sage: from matplotlib import rc
sage: rc('text', usetex=True)
sage: rc('text.latex', preamble=r'\usepackage{siunitx}')
sage: plot(sin(x), (x, 0, 4), axes_labels=[r'$\si{\volt}$', r'$\si{\second}$'])  # output is OK
Launched png viewer for Graphics object consisting of 1 graphics primitive
sage: text(r"\SI{1}{\ampere}", (2, 2))  # output is OK
Launched png viewer for Graphics object consisting of 1 graphics primitive

If you don't want to wait for the release of SageMath 8.4 (scheduled for October), the solution would be to use the development version of SageMath via

git clone 
cd sage
git checkout develop
git pull
MAKE="make -j8" make

(see here for more details).

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2018-09-20 05:18:56 -0500

Seen: 179 times

Last updated: Sep 22 '18