我必须在一个图中绘制多个数据集。能够突出显示一个或多个图以便比较它们是很有用的。为此,只要直接选择一条线,或者单击图例中的相应条目,我就会在":"
(背景图)和(突出显示的图)之间切换绘图的线型。"-"
这非常有效,直到我尝试使用bbox_to_anchor
. 在此之后,在图例线上单击鼠标会连续触发 2 次单击事件,从而取消切换效果。
如何在保持pick_event的正确行为的同时将图例放置在轴之外?
重现问题的简化代码(单击绘图线在“突出显示”和“未突出显示”之间切换,而单击图例线会在返回到先前状态之前短暂切换绘图线):
import pylab
import numpy
# Create data for plotting
t = numpy.linspace(0, 1.0, 100)
a = numpy.sin(2*numpy.pi*t)
# Set up figure
fig = pylab.figure()
ax = pylab.subplot(111)
# Plot figures
lines = []
for i in range(5):
line = ax.plot(t, (i+1)*a, linestyle=':', picker=5, label='line%d'%(i+1))
lines.append(line[0]) # Save plot lines
# Create legend
leg = ax.legend(bbox_to_anchor=(1.01, 1), loc=2) # Does not work as expected
# leg = ax.legend() # Works!!
# Get legend lines
leglines = leg.get_lines()
# Set event for legend lines
for line in leglines:
line.set_picker(5)
# Create a 2 way mapping between legend lines <-> plot lines
line2leg = dict(zip(lines+leglines, leglines+lines))
# Define event function
def onpick(event):
thisline = event.artist
if thisline.get_linestyle()==':':
print ": -> -" # For debugging
thisline.set_linestyle('-')
line2leg[thisline].set_linestyle('-')
else:
print "- -> :" # For debugging
thisline.set_linestyle(':')
line2leg[thisline].set_linestyle(':')
fig.canvas.draw()
# connect event function
fig.canvas.mpl_connect('pick_event', onpick)
pylab.show()