python绘制条件频率分布

时间:2014-05-19 21:48:18

标签: python matplotlib plot frequency-distribution

我对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'

有没有办法操纵条件频率分布?谢谢!

enter image description here

1 个答案:

答案 0 :(得分:1)

spines不是条件频率分布的元素,它们是绘制条件频率分布的轴的元素。您可以通过为轴分配变量来访问它们。下面是一个示例,另一个示例是here

还有一个复杂的问题。 cfd.plot()调用plt.show,立即显示该图。要在此之后更新它,您需要在interactive mode。根据您使用的backend,您可以使用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