【问题标题】:Matplotlib: Draggable is not working on multiple legends of plots which are generated with twinx()Matplotlib:Draggable 不适用于使用 twinx() 生成的多个图例图例
【发布时间】:2015-03-10 15:39:36
【问题描述】:

我有两个图例,如下图,我发现我无法拖动第一个图例,这是什么问题?如何处理?谢谢!

    import matplotlib.pyplot as plt

    fig1, ax1 = plt.subplots()
    ax2 = ax1.twinx()

    ax1.plot([1,2,3],[0.1,0.82,0.3],'y*', label="one")
    ax2.plot([1,2,3],[5,6,7],'ro', label="two")

    leg1 = ax1.legend()
    leg2 = ax2.legend()

    leg1.draggable(state=True)
    leg2.draggable(state=True)
    plt.show()

【问题讨论】:

    标签: python matplotlib plot legend


    【解决方案1】:

    这是双轴的一般限制。选择事件仅限于“顶部”轴。

    造成这种情况的原因有很多,但基本上归结为“需要进行大量重构才能进行更改,可能会以微妙的方式破坏向后兼容性,并且只会影响一些事情”。

    有一种解决方法,但它有点笨拙。我还将从第一个图例的顶部移动第二个图例。否则,我们将同时拖动它们。这是一个例子:

    import matplotlib.pyplot as plt
    
    class Workaround(object):
        def __init__(self, artists):
            self.artists = artists
            artists[0].figure.canvas.mpl_connect('button_press_event', self)
    
        def __call__(self, event):
            for artist in self.artists:
                artist.pick(event)
    
    fig1, ax1 = plt.subplots()
    ax2 = ax1.twinx()
    
    ax1.plot([1,2,3],[0.1,0.82,0.3],'y*', label="one")
    ax2.plot([1,2,3],[5,6,7],'ro', label="two")
    
    leg1 = ax1.legend()
    leg2 = ax2.legend(loc='upper left')
    
    leg1.draggable(True)
    leg2.draggable(True)
    
    draggable_workaround = Workaround([leg1, leg2])
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 1970-01-01
      相关资源
      最近更新 更多