Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib won't write \approx LaTeX character in legend? [duplicate]

For some reason I can't get matplotlib to write down the \approx LaTeX symbol in a legend.

Here's a MWE:

import matplotlib.pyplot as plt
plt.scatter([0.5, 0.5], [0.5, 0.5], label='$U_{c} \approx %0.1f$' % 22)
#plt.scatter([0.5, 0.5], [0.5, 0.5], label='$U_{c} \simeq %0.1f$' % 22)
#plt.scatter([0.5, 0.5], [0.5, 0.5], label='$U_{c} \sim %0.1f$' % 22)
plt.legend(fancybox=True, loc='upper right', scatterpoints=1, fontsize=16)
plt.show()

Notice the first line will not show the \approx character or the value after it but both \simeq and \sim work fine.

I've just opened a new issue in matplotlib's Github but it occurred to me that I might be doing something wrong so I better ask. If I am, I'll delete close it.

like image 348
Gabriel Avatar asked Jan 10 '23 05:01

Gabriel


1 Answers

Try using a raw string literal: r'$U_{c} \approx %0.1f$'.

In [8]: plt.scatter([0.5, 0.5], [0.5, 0.5], label=r'$U_{c} \approx %0.1f$'%22)
Out[8]: <matplotlib.collections.PathCollection at 0x7f799249e550>
In [9]: plt.legend(fancybox=True, loc='best')
Out[9]: <matplotlib.legend.Legend at 0x7f79925e1550>
In [10]: plt.show()

enter image description here

The reason this is happening is as follows:

  • Without the r infront of the string literal, the string is interpreted by the interpreter as:

    '$U_{c} ' + '\a' + 'pprox 22.0$'

  • The '\a' is a special escaped character for the ASCII Bell: BEL.

  • This interpreted string is then passed to the TeX parser. However, because '\approx' got mashed up, the TeX parser doesn't know how to convert your string to proper TeX.

To make sure backslashes (\) in the string aren't creating weird escaped characters, add the r out front.

like image 190
wflynny Avatar answered Jan 27 '23 00:01

wflynny