python - Matplotlib:Draggable 不适用于使用 twinx() 生成的多个图例

标签 python matplotlib plot legend

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

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

最佳答案

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

这有几个原因,但基本上可以归结为“需要大量重构才能改变,可能会以一种微妙的方式破坏向后兼容性,而且它只会影响一些事情”。

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

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

关于python - Matplotlib:Draggable 不适用于使用 twinx() 生成的多个图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28967911/

相关文章:

python - Pandas :将单元格值与同一列下方的单元格值进行比较?

matplotlib 添加艺术家不在图例上显示标签

Python:ValueError:无法将字符串转换为 float : '0'

R:子集化和绘制 SpatialPoints 对象

r - ggplot2 中的平滑和连续颜色渐变

python - 组合两个数据帧时保留索引

python - PyQt 如何在 closeEvent 中获取发件人(小部件)?

python - 分组转移 Pandas

python - 更改 Seaborn Boxplot 上的框和点分组色调

r - 在绘图 R 中省略坐标轴