您已经在使用当前代码的正确轨道上。基本上,您只是
plt.draw()在
onpick函数中缺少对的调用。
但是,在我们的评论讨论中,
mpldatacursor出现了,您询问了一个以这种方式做事的例子。
目前
HighlightingDataCursor在
mpldatacursor设置围绕突出的整个的思想
Line2D的艺术家,它不只是一个特定的索引。(这故意受到限制,因为在matplotlib中没有为任何艺术家绘制任意高光的好方法,因此我将高光部分保持较小。)
但是,您可以将类似于此的子类化(假设您正在使用,
plot并且希望使用每个轴上绘制的第一件事)。我还要说明如何使用
point_labels,以防每个显示点都有不同的标签。
import numpy as npimport matplotlib.pyplot as pltfrom mpldatacursor import HighlightingDataCursor, DataCursordef main(): fig, axes = plt.subplots(nrows=2, ncols=2) for ax, marker in zip(axes.flat, ['o', '^', 's', '*']): x, y = np.random.random((2,20)) ax.plot(x, y, ls='', marker=marker) IndexedHighlight(axes.flat, point_labels=[str(i) for i in range(20)]) plt.show()class IndexedHighlight(HighlightingDataCursor): def __init__(self, axes, **kwargs): # Use the first plotted Line2D in each axes artists = [ax.lines[0] for ax in axes] kwargs['display'] = 'single' HighlightingDataCursor.__init__(self, artists, **kwargs) self.highlights = [self.create_highlight(artist) for artist in artists] plt.setp(self.highlights, visible=False) def update(self, event, annotation): # Hide all other annotations plt.setp(self.highlights, visible=False) # Highlight everything with the same index. artist, ind = event.artist, event.ind for original, highlight in zip(self.artists, self.highlights): x, y = original.get_data() highlight.set(visible=True, xdata=x[ind], ydata=y[ind]) DataCursor.update(self, event, annotation)main()
同样,这假设您正在使用
plot而不是
scatter。可以使用进行此操作
scatter,但是您需要更改大量令人讨厌的细节。(没有突出显示任意matplotlib艺术家的通用方法,因此您必须有很多非常冗长的代码才能分别处理每种类型的艺术家。)
希望它是有用的,无论如何。



