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.
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()
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
.
'\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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With