Secondary axis with twinx(): how to add to legend?

前端 未结 6 1704
日久生厌
日久生厌 2020-11-22 14:55

I have a plot with two y-axes, using twinx(). I also give labels to the lines, and want to show them with legend(), but I only succeed to get the l

6条回答
  •  温柔的废话
    2020-11-22 15:27

    You can easily get what you want by adding the line in ax:

    ax.plot([], [], '-r', label = 'temp')
    

    or

    ax.plot(np.nan, '-r', label = 'temp')
    

    This would plot nothing but add a label to legend of ax.

    I think this is a much easier way. It's not necessary to track lines automatically when you have only a few lines in the second axes, as fixing by hand like above would be quite easy. Anyway, it depends on what you need.

    The whole code is as below:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import rc
    rc('mathtext', default='regular')
    
    time = np.arange(22.)
    temp = 20*np.random.rand(22)
    Swdown = 10*np.random.randn(22)+40
    Rn = 40*np.random.rand(22)
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax2 = ax.twinx()
    
    #---------- look at below -----------
    
    ax.plot(time, Swdown, '-', label = 'Swdown')
    ax.plot(time, Rn, '-', label = 'Rn')
    
    ax2.plot(time, temp, '-r')  # The true line in ax2
    ax.plot(np.nan, '-r', label = 'temp')  # Make an agent in ax
    
    ax.legend(loc=0)
    
    #---------------done-----------------
    
    ax.grid()
    ax.set_xlabel("Time (h)")
    ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
    ax2.set_ylabel(r"Temperature ($^\circ$C)")
    ax2.set_ylim(0, 35)
    ax.set_ylim(-20,100)
    plt.show()
    

    The plot is as below:

    enter image description here


    Update: add a better version:

    ax.plot(np.nan, '-r', label = 'temp')
    

    This will do nothing while plot(0, 0) may change the axis range.


    One extra example for scatter

    ax.scatter([], [], s=100, label = 'temp')  # Make an agent in ax
    ax2.scatter(time, temp, s=10)  # The true scatter in ax2
    
    ax.legend(loc=1, framealpha=1)
    

提交回复
热议问题