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

和自甴很熟 提交于 2019-12-10 15:50:32

问题


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.


回答1:


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.

  • 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.



来源:https://stackoverflow.com/questions/24739216/matplotlib-wont-write-approx-latex-character-in-legend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!