首页 > 解决方案 > 在 Python 中可视化文本数据集中最常见的单词

问题描述

我有一个包含年份和文本(演讲稿)的 csv。

我已将其加载到 Dataframe 并完成预处理。

然后,我有一个新的数据框,其中包含单词及其每年的频率,如下所示,

在此处输入图像描述

“单词”列包含原始单词。而像“1970”这样的列包含了该“单词”在该特定年份的演讲中出现的频率。因此,“年份”列包含“单词”列中提到的单词的频率。

现在,我想在一个情节中可视化每年所说的前五个单词。它可以是任何类型的可视化,如散点图。所有数据在一个带有 2 个轴的图中,x 轴是年份,y 轴是频率和数据点旁边或图例中的单词。

有没有办法在 python 中做到这一点?

标签: nlpdata-visualizationvisualization

解决方案


您可以使用annotate为点添加标签。其余的只是管道,例如

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 = df.nlargest(n, columns=str(year))
    plt.scatter([year]*n, top5[str(year)])
    for _,row in top5.iterrows():
        plt.annotate(row['word'], (year, row[str(year)]))

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

推荐阅读