Showing legend for only one subplot using matplotlib

后端 未结 2 1697
误落风尘
误落风尘 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 13:50

    If I understand correctly, you need to tell plt.legend what to put as legends... at this point it is being loaded empty. What you get must be from another source. I have quickly the following, and of course when I run fig.legend as you do I get nothing.

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    ax1 = fig.add_axes([0.1, 0.1, 0.4, 0.7])
    ax2 = fig.add_axes([0.55, 0.1, 0.4, 0.7])
    
    x = np.arange(0.0, 2.0, 0.02)
    y1 = np.sin(2*np.pi*x)
    y2 = np.exp(-x)
    l1, l2 = ax1.plot(x, y1, 'rs-', x, y2, 'go')
    
    y3 = np.sin(4*np.pi*x)
    y4 = np.exp(-2*x)
    l3, l4 = ax2.plot(x, y3, 'yd-', x, y4, 'k^')
    
    fig.legend(loc='upper right', fontsize='x-large')
    
    #fig.legend((l1, l2), ('Line 1', 'Line 2'), 'upper left')
    #fig.legend((l3, l4), ('Line 3', 'Line 4'), 'upper right')
    plt.show()
    

    I'd suggest doing one by one, and then applying for all.

提交回复
热议问题