【问题标题】:Secondary axis with twinx(): how to add to legend?带有 twinx() 的辅助轴:如何添加到图例中?
【发布时间】:2021-03-03 20:03:54
【问题描述】:

我有一个带有两个 y 轴的图,使用 twinx()。我也给线条打了标签,想用legend()显示出来,但我只成功得到了图例中一个轴的标签:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')
ax.legend(loc=0)
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()

所以我只得到图例中第一个轴的标签,而不是第二个轴的标签“temp”。如何将第三个标签添加到图例中?

【问题讨论】:

  • [不要在任何靠近任何生产代码的地方这样做] 当我唯一的目标是尽快用适当的图例生成一个漂亮的情节时,我会使用一个丑陋的用我在ax2 上使用的样式在ax 上绘制一个空数组的技巧:在你的情况下,ax.plot([], [], '-r', label = 'temp')。它比正确执行要快得多,也更简单...
  • 对于 pandas 和 twinx,另见 stackoverflow.com/a/57484812/3642162

标签: python matplotlib axis legend


【解决方案1】:

准备

import numpy as np
from matplotlib import pyplot as plt

fig, ax1 = plt.subplots( figsize=(15,6) )

Y1, Y2 = np.random.random((2,100))

ax2 = ax1.twinx()

内容

我很惊讶它到目前为止没有出现,但最简单的方法是手动将它们收集到一个轴 obj 中(它们彼此重叠)

l1 = ax1.plot( range(len(Y1)), Y1, label='Label 1' )
l2 = ax2.plot( range(len(Y2)), Y2, label='Label 2', color='orange' )

ax1.legend( handles=l1+l2 )

或者通过fig.legend() 将它们自动收集到周围的图形中,并使用bbox_to_anchor 参数摆弄:

ax1.plot( range(len(Y1)), Y1, label='Label 1' )
ax2.plot( range(len(Y2)), Y2, label='Label 2', color='orange' )

fig.legend( bbox_to_anchor=(.97, .97) )

完成

fig.tight_layout()
fig.savefig('stackoverflow.png', bbox_inches='tight')

【讨论】:

    【解决方案2】:

    正如 matplotlib.org 的 example 中所提供的,从多个轴实现单个图例的简洁方法是使用绘图句柄:

    import matplotlib.pyplot as plt
    
    
    fig, ax = plt.subplots()
    fig.subplots_adjust(right=0.75)
    
    twin1 = ax.twinx()
    twin2 = ax.twinx()
    
    # Offset the right spine of twin2.  The ticks and label have already been
    # placed on the right by twinx above.
    twin2.spines.right.set_position(("axes", 1.2))
    
    p1, = ax.plot([0, 1, 2], [0, 1, 2], "b-", label="Density")
    p2, = twin1.plot([0, 1, 2], [0, 3, 2], "r-", label="Temperature")
    p3, = twin2.plot([0, 1, 2], [50, 30, 15], "g-", label="Velocity")
    
    ax.set_xlim(0, 2)
    ax.set_ylim(0, 2)
    twin1.set_ylim(0, 4)
    twin2.set_ylim(1, 65)
    
    ax.set_xlabel("Distance")
    ax.set_ylabel("Density")
    twin1.set_ylabel("Temperature")
    twin2.set_ylabel("Velocity")
    
    ax.yaxis.label.set_color(p1.get_color())
    twin1.yaxis.label.set_color(p2.get_color())
    twin2.yaxis.label.set_color(p3.get_color())
    
    tkw = dict(size=4, width=1.5)
    ax.tick_params(axis='y', colors=p1.get_color(), **tkw)
    twin1.tick_params(axis='y', colors=p2.get_color(), **tkw)
    twin2.tick_params(axis='y', colors=p3.get_color(), **tkw)
    ax.tick_params(axis='x', **tkw)
    
    ax.legend(handles=[p1, p2, p3])
    
    plt.show()
    

    【讨论】:

      【解决方案3】:

      在ax中添加一行就可以轻松得到你想要的:

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

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

      这只会在 ax 的图例中添加一个标签。

      我认为这是一种更简单的方法。 当第二个轴只有几条线时,没有必要自动跟踪线,因为像上面这样手动修复会很容易。无论如何,这取决于你需要什么。

      整个代码如下:

      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()
      

      剧情如下:


      更新:添加更好的版本:

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

      plot(0, 0) 可能会改变轴范围时,这不会做任何事情。


      一个额外的分散示例

      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)
      

      【讨论】:

      • 我喜欢这个。它“欺骗”系统的方式有点丑陋,但实现起来非常简单。
      • 这实现起来非常简单。但是当将它与 scatter 一起使用时,图例中产生的 scatter 大小只是一个很小的点。
      • @greeeeeeen 然后你应该在制作散点图时指定标记大小:-)
      • @SyrtisMajor 我当然试过了。但这并没有改变图例中的标记大小。
      • @greeeeeeen 您是否更改了代理分散的标记大小?查看我的帖子,我添加了一个示例代码的 sn-p。
      【解决方案4】:

      从 matplotlib 2.1 版开始,您可以使用图形图例。而不是ax.legend(),它会生成一个带有来自轴ax 的句柄的图例,可以创建一个图形图例

      fig.legend(loc="右上角")

      这将从图中的所有子图中收集所有句柄。由于是图例,所以会放在图的一角,loc参数是相对于图的。

      import numpy as np
      import matplotlib.pyplot as plt
      
      x = np.linspace(0,10)
      y = np.linspace(0,10)
      z = np.sin(x/3)**2*98
      
      fig = plt.figure()
      ax = fig.add_subplot(111)
      ax.plot(x,y, '-', label = 'Quantity 1')
      
      ax2 = ax.twinx()
      ax2.plot(x,z, '-r', label = 'Quantity 2')
      fig.legend(loc="upper right")
      
      ax.set_xlabel("x [units]")
      ax.set_ylabel(r"Quantity 1")
      ax2.set_ylabel(r"Quantity 2")
      
      plt.show()
      

      为了将图例放回坐标区,需要提供bbox_to_anchorbbox_transform。后者将是图例应驻留的轴的轴变换。前者可能是由loc 定义的边缘坐标,以轴坐标给出。

      fig.legend(loc="upper right", bbox_to_anchor=(1,1), bbox_transform=ax.transAxes)
      

      【讨论】:

      • 那么,2.1 版已经发布了吗?但是在 Anaconda 3 中,我尝试了 conda upgrade matplotlib 没有找到更新的版本,我仍在使用 v.2.0.2
      • 这是实现最终结果的一种更简洁的方式。
      • 漂亮又蟒蛇
      • 当您有许多子图时,这似乎不起作用。它为所有子图添加了一个图例。通常每个子图都需要一个图例,每个图例的主轴和次轴都包含系列。
      • @sancho 正确,这就是这个答案的第三句中所写的内容,“......这将收集图中所有子图的所有句柄。”。
      【解决方案5】:

      一个可能适合您需求的快速破解..

      取下盒子的框架并手动将两个图例放在一起。像这样的..

      ax1.legend(loc = (.75,.1), frameon = False)
      ax2.legend( loc = (.75, .05), frameon = False)
      

      其中 loc 元组是从左到右和从下到上的百分比,表示图表中的位置。

      【讨论】:

        【解决方案6】:

        我找到了以下官方 matplotlib 示例,它使用 host_subplot 在一个图例中显示多个 y 轴和所有不同的标签。无需解决方法。到目前为止我找到的最佳解决方案。 http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html

        from mpl_toolkits.axes_grid1 import host_subplot
        import mpl_toolkits.axisartist as AA
        import matplotlib.pyplot as plt
        
        host = host_subplot(111, axes_class=AA.Axes)
        plt.subplots_adjust(right=0.75)
        
        par1 = host.twinx()
        par2 = host.twinx()
        
        offset = 60
        new_fixed_axis = par2.get_grid_helper().new_fixed_axis
        par2.axis["right"] = new_fixed_axis(loc="right",
                                            axes=par2,
                                            offset=(offset, 0))
        
        par2.axis["right"].toggle(all=True)
        
        host.set_xlim(0, 2)
        host.set_ylim(0, 2)
        
        host.set_xlabel("Distance")
        host.set_ylabel("Density")
        par1.set_ylabel("Temperature")
        par2.set_ylabel("Velocity")
        
        p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
        p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
        p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")
        
        par1.set_ylim(0, 4)
        par2.set_ylim(1, 65)
        
        host.legend()
        
        plt.draw()
        plt.show()
        

        【讨论】:

        • 欢迎来到 Stack Overflow!请引用链接中最相关的部分,以防目标站点无法访问或永久离线。见How do I write a good answer。以后多关注当下的问题,这个已经快4年了。
        • 确实是一个不错的发现,但我希望您能从示例中学到什么,将其应用于 OP 的 MWE,并包含一张图片。
        【解决方案7】:

        我不确定此功能是否是新功能,但您也可以使用 get_legend_handles_labels() 方法,而不是自己跟踪线条和标签:

        import numpy as np
        import matplotlib.pyplot as plt
        from matplotlib import rc
        rc('mathtext', default='regular')
        
        pi = np.pi
        
        # fake data
        time = np.linspace (0, 25, 50)
        temp = 50 / np.sqrt (2 * pi * 3**2) \
                * np.exp (-((time - 13)**2 / (3**2))**2) + 15
        Swdown = 400 / np.sqrt (2 * pi * 3**2) * np.exp (-((time - 13)**2 / (3**2))**2)
        Rn = Swdown - 10
        
        fig = plt.figure()
        ax = fig.add_subplot(111)
        
        ax.plot(time, Swdown, '-', label = 'Swdown')
        ax.plot(time, Rn, '-', label = 'Rn')
        ax2 = ax.twinx()
        ax2.plot(time, temp, '-r', label = 'temp')
        
        # ask matplotlib for the plotted objects and their labels
        lines, labels = ax.get_legend_handles_labels()
        lines2, labels2 = ax2.get_legend_handles_labels()
        ax2.legend(lines + lines2, labels + labels2, loc=0)
        
        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()
        

        【讨论】:

        • 这是唯一可以处理图与图例重叠的轴的解决方案(最后一个轴是应该绘制图例的轴)
        • 此解决方案也适用于errorbar 绘图,而接受的绘图则失败(分别显示一行及其错误栏,并且没有一个带有正确标签)。另外,它更简单。
        • 小问题:如果你想覆盖 ax2 的标签并且它从一开始就没有一组标签,它就不起作用
        • 备注:经典情节无需指定label参数。但对于其他人,例如。你需要的酒吧。
        • 如果您事先不知道要绘制多少行,这也会让一切变得更容易。
        【解决方案8】:

        您可以通过添加以下行轻松添加第二个图例:

        ax2.legend(loc=0)
        

        你会得到这个:

        但是,如果您想要一个图例上的所有标签,那么您应该这样做:

        import numpy as np
        import matplotlib.pyplot as plt
        from matplotlib import rc
        rc('mathtext', default='regular')
        
        time = np.arange(10)
        temp = np.random.random(10)*30
        Swdown = np.random.random(10)*100-10
        Rn = np.random.random(10)*100-10
        
        fig = plt.figure()
        ax = fig.add_subplot(111)
        
        lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
        lns2 = ax.plot(time, Rn, '-', label = 'Rn')
        ax2 = ax.twinx()
        lns3 = ax2.plot(time, temp, '-r', label = 'temp')
        
        # added these three lines
        lns = lns1+lns2+lns3
        labs = [l.get_label() for l in lns]
        ax.legend(lns, labs, loc=0)
        
        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()
        

        这会给你这个:

        【讨论】:

        • 这会因errorbar 绘图而失败。有关正确处理它们的解决方案,请参见下文:stackoverflow.com/a/10129461/1319447
        • 为了防止两个重叠的图例,在我指定两个 .legend(loc=0) 的情况下,您应该为图例位置值指定两个不同的值(都不是 0)。见:matplotlib.org/api/legend_api.html
        • 我在将单行添加到具有多行 ax1 的某些子图中时遇到了一些麻烦。在这种情况下,请使用 lns1=ax1.lines,然后将 lns2 附加到此列表中。
        • loc使用的不同值解释here
        • 查看下面的答案以获得更自动的方式(使用 matplotlib >= 2.1):stackoverflow.com/a/47370214/653364
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-28
        • 2020-11-09
        • 2022-06-28
        相关资源
        最近更新 更多