Showing legend for only one subplot using matplotlib

后端 未结 2 1698
误落风尘
误落风尘 2021-01-25 13:38

I\'m facing a problem in showing the legend in the correct format using matplotlib.

EDIT: I have 4 subplots in a figure in 2 by 2 format and I want legend only on the f

2条回答
  •  一个人的身影
    2021-01-25 14:06

    It is useful to work with the axes directly (ax in your case) when when working with subplots. So if you set up two plots in a figure and only wish to have a legend in your second plot:

    t = np.linspace(0, 10, 100)
    
    plt.figure()
    
    ax1 = plt.subplot(2, 1, 1)
    ax1.plot(t, t * t)
    
    ax2 = plt.subplot(2, 1, 2)
    ax2.plot(t, t * t * t)
    ax2.legend('Cubic Function')
    

    Note that when creating the legend, I am doing so on ax2 as opposed to plt. If you wish to create a second legend for the first subplot, you can do so in the same way but on ax1.

提交回复
热议问题