原始问题已被编辑,此答案已更新以反映这一点。
当尝试在 matplotlib 中使用 LaTeX 格式时,您必须使用原始字符串,表示为r""
.
下面给出的代码将迭代range(4)
并使用绘图i'th
均值和方差(正如您最初所做的那样)。它还将设置label
对于每个图使用label=r'$v_{}$'.format(i+1)
. This 字符串格式化 https://docs.python.org/3.4/library/functions.html#format只需替换{}
与里面所谓的任何东西format
, 在这种情况下i+1
。通过这种方式,您可以自动化绘图的标签。
我已经删除了plt.axvline(...)
, plt.xlabel(...)
and plt.ylabel(...)
出于for
循环,因为您只需要调用它一次。我也删除了plt.legend()
来自for
出于同样的原因循环并删除了它的参数。如果您提供关键字参数label
to plt.plot()
然后您可以在绘制图时单独标记它们。
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
mean = [10,12,16,22,25]
variance = [3,6,8,10,12]
x = np.linspace(0,40,1000)
for i in range(4):
sigma = np.sqrt(variance[i])
y = mlab.normpdf(x,mean[i],sigma)
plt.plot(x,y, label=r'$v_{}$'.format(i+1))
plt.xlabel("X")
plt.ylabel("P(X)")
plt.axvline(x=15, ymin=0, ymax=1,ls='--',c='black')
plt.legend()
plt.show()