Python 如何在 .py 文件中使用 Matplotlib 在绘图图例中编写 Latex 公式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14016217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file?
提问by Titianne
I am writing a script in Python (.py file) and I am using Matplotlib to plot an array. I want to add a legend with a formula to the plot, but I haven't been able to do it. I have done this before in IPython or the terminal. In this case, writing something like this:
我正在用 Python(.py 文件)编写一个脚本,我正在使用 Matplotlib 来绘制一个数组。我想在情节中添加一个带有公式的图例,但我一直无法做到。我之前在 IPython 或终端中做过这个。在这种情况下,编写如下内容:
legend(ur'$The_formula$')
worked perfectly. However, this doesn't work when I call my .py script from the terminal/IPython.
完美地工作。但是,当我从终端/IPython 调用我的 .py 脚本时,这不起作用。
采纳答案by tacaswell
The easiest way is to assign the label when you plot the data, e.g.:
最简单的方法是在绘制数据时分配标签,例如:
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()
回答by Titianne
When writing code for labels it is:
为标签编写代码时,它是:
import pylab
# code here
pylab.plot(x,y,'f:', '$sin(x)$')
So perhaps pylab.legend('$latex here$')
所以也许 pylab.legend('$latex here$')
Edit:
编辑:
The uis for unicode strings, try just r'$\latex$'
的u是Unicode字符串,尽量只r'$\latex$'

