[英]Why will my legend not move in Python
我必须创建一个简单的图来学习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.
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”方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.