首页 > 解决方案 > python,nltk,单词频率的多重绘图结果(子图)

问题描述

我正在尝试将每个文本中的 most_common(10) 单词可视化。这是我的代码。
(我使用 nltk.corpus.gutenberg 所有文本)

from nltk.corpus import gutenberg
import matplotlib.pyplot as plt
from nltk import ConditionalFreqDist
from nltk.corpus import stopwords
%matplotlib inline

stop_words = set(stopwords.words('English'))

cfd = ConditionalFreqDist((target[:-4], word.lower())
                         for target in gutenberg.fileids()
                         for word in gutenberg.words(target)
                         if word.lower() not in stop_words
                         and word.isalpha())

plt.figure(figsize = (10,10))
for i, title in enumerate(list(cfd.keys())):
    plt.subplot(6,3,i+1)
    cfd[title].plot(10)

我想使用 subplot 绘制 6x3,但结果始终是 18x1。有什么好的方法吗?谢谢。

标签: pythonplotnltkvisualization

解决方案


我能够使用 subplot2grid 的方式是将 plt.subplot() 调用替换为 subplot2grid 调用。以下是我如何让它工作:

plt.figure(figsize = (6,3))
for i, title in enumerate(list(cfd.keys())):
    #     plt.subplot(6,3,i+1)
    plt.subplot2grid((6,3),(0,0), rowspan=10, colspan=10)
    cfd[title].plot(10, title=title)

这是 subplot2grid 示例的一般用途: # 用不同大小的子图绘制图形 fig = plt.figure(1) # 设置子图网格 gridspec.GridSpec(3,3)

# large subplot
plt.subplot2grid((3,3), (0,0), colspan=2, rowspan=3)

推荐阅读