matplotlib不会在图例中写入\ approx LaTeX字符吗? [英] matplotlib won't write \approx LaTeX character in legend?

查看:149
本文介绍了matplotlib不会在图例中写入\ approx LaTeX字符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,我无法获得matplotlib在图例中写下\approx LaTeX符号.

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

这是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()

请注意,第一行将不显示\approx字符或其后的值,但是\simeq\sim都可以正常工作.

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

我刚刚在matplotlib的Github中打开了新问题,但是我想到我可能做错了什么,所以我最好问一下.如果是,我将删除将其关闭.

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.

推荐答案

尝试使用原始字符串文字:r'$U_{c} \approx %0.1f$'.

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:

  • 在字符串文字的前面没有r的情况下,解释器会将字符串解释为:

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

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

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

'\a'是ASCII贝尔的特殊转义字符:BEL.

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

要确保字符串中的反斜杠(\)不会创建奇怪的转义字符,请在前面添加r.

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

这篇关于matplotlib不会在图例中写入\ approx LaTeX字符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆