How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file?

匆匆过客 提交于 2021-02-17 08:34:08

问题


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:

legend(ur'$The_formula$')

worked perfectly. However, this doesn't work when I call my .py script from the terminal/IPython.


回答1:


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



回答2:


When writing code for labels it is:

import pylab

# code here

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

So perhaps pylab.legend('$latex here$')

Edit:

The u is for unicode strings, try just r'$\latex$'



来源:https://stackoverflow.com/questions/14016217/how-do-i-write-a-latex-formula-in-the-legend-of-a-plot-using-matplotlib-inside-a

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