为什么我的传奇不会搬进来 Python

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. 并且你将无法移动你的图例。因此,您可以通过执行以下操作轻松更改此设置:

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' 方式。