[英]How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file?
I am writing a script in Python (.py file) and I am using Matplotlib to plot an array. 我正在用Python编写脚本(.py文件),我正在使用Matplotlib来绘制数组。 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.
我之前在IPython或终端中做过这个。 In this case, writing something like this:
在这种情况下,写这样的东西:
legend(ur'$The_formula$')
worked perfectly. 工作得很好。 However, this doesn't work when I call my .py script from the terminal/IPython.
但是,当我从终端/ IPython调用我的.py脚本时,这不起作用。
The easiest way is to assign the label when you plot the data, eg: 最简单的方法是在绘制数据时分配标签,例如:
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()
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 u
is for unicode strings, try just r'$\\latex$'
u
是unicode字符串,试试r'$\\latex$'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.