如何响应python中鼠标指针的悬停在绘图上显示注释?

2024-04-26 00:02:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv包含年份和文本(演讲稿)。你知道吗

我已经将其加载到数据帧中并完成了预处理。你知道吗

然后,我有一个新的数据框,包含单词和它们每年的频率,看起来像这样

enter image description here

“word”列包含原始单词。像“1970”这样的栏目包含了“单词”在那一年的演讲中出现的频率。因此,“年”列包含“词”列中提到的词的频率。你知道吗

我把每年说的前五个词想象成一个情节。一个图形中的所有数据都有两个轴,x轴是年份,y轴是频率和数据点旁边或图例中的单词。你知道吗

我想更改这些对鼠标悬停敏感的注释。它应该只在鼠标悬停在它们上面时显示。现在是这样, enter image description here

注释和要点已完成。尝试了一个或多个事件都不起作用。你知道吗

import matplotlib.pyplot as plt

RANGE=(1970, 1974)
plt.xticks(range(*RANGE))
plt.xlim(RANGE)

def show(year, n=5):
"Add the top-n words for a year to the current plot"
 top5 = freqs_df.nlargest(n, columns=year)
 plt.scatter([year]*n, top5[year],picker=True)
 for _,row in top5.iterrows():
    annotate = plt.annotate(row['word'], (year, row[year]))
    annotate.set_visible(True)


for year in range(*RANGE):
  show(year)

 plt.show()

用悬停代替标注在整个绘图中。你知道吗

这不是Possible to make labels appear when hovering over a point in matplotlib?中提到的。这个问题的答案并不是我们想要的,因为它只响应“点击”而不是“悬停”。你知道吗


Tags: 数据informatplotlibshowrangeplt单词