Python绘制条件频率分布

0 投票
1 回答
2385 浏览
提问于 2025-04-18 07:02

我刚开始学习Python,所以正在研究nltk这本书。同时,我也在尝试熟悉如何处理图形和图表。我绘制了一个条件频率分布图,现在我想先去掉图的上边和左边的边框。这是我现在的代码:

import nltk
import sys
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import show
from nltk.corpus import state_union

#cfdist1
cfd = nltk.ConditionalFreqDist(
    (word, fileid[:4])
    for fileid in state_union.fileids()
    for w in state_union.words(fileid)
    for word in ['men', 'women', 'people']
    if w.lower().startswith(word))
cfd.plot()


 for loc, spine in cfd.spines.items():
    if loc in ['left','bottom']:
        spine.set_position(('outward',0)) # outward by 0
    elif loc in ['right','top']:
        spine.set_color('none') # don't draw spine
    else:
        raise ValueError('unknown spine location: %s'%loc)

但是我遇到了以下错误:

AttributeError: 'ConditionalFreqDist' object has no attribute 'spines'

有没有办法可以处理条件频率分布呢?谢谢!

在这里输入图片描述

1 个回答

1

在这里,spines(脊柱)并不是条件频率分布的一个元素,而是绘制条件频率分布的坐标轴上的一部分。你可以通过给坐标轴赋值一个变量来访问它们。下面有一个示例,另外还有一个示例在这里

还有一个额外的复杂性。cfd.plot()会调用plt.show,这会立即显示图形。如果你想在这之后更新图形,你需要进入交互模式。根据你使用的后端,你可能可以通过plt.ion()来开启交互模式。下面的示例在MacOSX、Qt4Agg等环境下可以正常工作,但我没有测试过其他环境。你可以通过matplotlib.get_backend()来查看你正在使用的后端。

import nltk
import matplotlib.pyplot as plt
from nltk.corpus import state_union

plt.ion() # turns interactive mode on

#cfdist1
cfd = nltk.ConditionalFreqDist(
    (word, fileid[:4])
    for fileid in state_union.fileids()
    for w in state_union.words(fileid)
    for word in ['men', 'women', 'people']
    if w.lower().startswith(word))

ax = plt.axes()
cfd.plot()

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.set_title('A Title')

plt.draw() # update the plot
plt.savefig('cfd.png') # save the updated figure

enter image description here

撰写回答