Matplotlib:Draggable 不适用于使用 twinx() 生成的多个图例
Matplotlib: Draggable is not working on multiple legends of plots which are generated with twinx()
我有两个图例,如下图,我发现我无法拖动第一个图例,这是什么问题?如何处理?谢谢!
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()
这是孪生轴的一般限制。选择事件仅限于 "top" 轴。
这有几个原因,但基本上可以归结为 "it takes a good deal of refactoring to change, might break backwards compatibility in a subtle way, and it only impacts a few things"。
有一个解决方法,但有点笨拙。我还将把第二个图例从第一个图例上移开。否则,我们将同时拖动它们。这是一个例子:
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()
我有两个图例,如下图,我发现我无法拖动第一个图例,这是什么问题?如何处理?谢谢!
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()
这是孪生轴的一般限制。选择事件仅限于 "top" 轴。
这有几个原因,但基本上可以归结为 "it takes a good deal of refactoring to change, might break backwards compatibility in a subtle way, and it only impacts a few things"。
有一个解决方法,但有点笨拙。我还将把第二个图例从第一个图例上移开。否则,我们将同时拖动它们。这是一个例子:
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()