我必须创建一个简单的图表来学习 python 中绘图的属性。这些属性之一是图例放置。其代码是 ax.legend(loc="some number")。我提到的那段代码中输入的不同数字决定了图例的放置位置。然而,无论我输入什么数字,我的传奇永远不会改变位置。我是否遗漏了更深层次的问题,或者我的程序是否有问题?
def line_plot():
x=np.linspace(-np.pi,np.pi,30)
cosx=np.cos(x)
sinx=np.sin(x)
fig1, ax1 = plt.subplots()
ax1.plot(x,np.sin(x), c='r', lw=3)
ax1.plot(x,np.cos(x), c='b', lw=3)
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.legend(["cos","sin"])
ax1.legend(loc=0);
ax1.set_xlim([-3.14, 3.14])
ax1.set_xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
ax1.grid(True)
ax1.set_xticklabels(['-'+r'$\pi$', '-'+r'$\pi$'+'/2',0, r'$\pi$'+'/2', r'$\pi$'])
plt.show()
return
if __name__ == "__main__":
line_plot()
最佳答案
当您绘制数据时,您需要给它们一个 label
为了让传说出现。如果你不这样做,那么你会得到 UserWarning: No labelled objects found. Use label='...' kwarg on individual plots.
你将无法移动你的传奇。因此,您可以通过执行以下操作轻松更改此设置:
def line_plot():
x=np.linspace(-np.pi,np.pi,30)
cosx=np.cos(x)
sinx=np.sin(x)
fig1, ax1 = plt.subplots()
ax1.plot(x,np.sin(x), c='r', lw=3,label='cos') #added label here
ax1.plot(x,np.cos(x), c='b', lw=3,label='sin') #added label here
ax1.set_xlabel('x')
ax1.set_ylabel('y')
#ax1.legend(["cos","sin"]) #don't need this as the plots are already labelled now
ax1.legend(loc=0);
ax1.set_xlim([-3.14, 3.14])
ax1.set_xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
ax1.grid(True)
ax1.set_xticklabels(['-'+r'$\pi$', '-'+r'$\pi$'+'/2',0, r'$\pi$'+'/2', r'$\pi$'])
plt.show()
return
if __name__ == "__main__":
line_plot()
这给出了下面的图。现在更改 loc
的值更改图例的位置。
编辑:
1)我给了你自己绘制的每组数据label
。然后当你到达 ax1.legend(loc=0)
行时然后,matplotlib 设置图例以在图例上包含这些标签。这是绘制图例的最“Pythonic”方式。
关于python - 为什么我的传奇在Python中不动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35759038/