如何在.py文件中使用Matplotlib在图表的图例中编写Latex公式?

问题描述 投票:21回答:2

我正在用Python编写脚本(.py文件),我正在使用Matplotlib来绘制数组。我想在情节中添加带有公式的图例,但我无法做到。我之前在IPython或终端中做过这个。在这种情况下,写这样的东西:

legend(ur'$The_formula$')

工作得很好。但是,当我从终端/ IPython调用我的.py脚本时,这不起作用。

python matplotlib latex
2个回答
26
投票

最简单的方法是在绘制数据时分配标签,例如:

import matplotlib.pyplot as plt
ax = plt.gca()  # or any other way to get an axis object
ax.plot(x, y, label=r'$\sin (x)$')

ax.legend()

5
投票

为标签编写代码时,它是:

import pylab

# code here

pylab.plot(x,y,'f:', '$sin(x)$')

所以也许pylab.legend('$latex here$')

编辑:

u用于unicode字符串,只需使用r'$\latex$'

© www.soinside.com 2019 - 2024. All rights reserved.