【问题标题】:python plotting conditional frequency distributionspython绘制条件频率分布
【发布时间】:2014-07-08 00:06:03
【问题描述】:

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

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

【问题讨论】:

  • 正在删除您的 cmets 吗?您遇到的问题是因为使用 draw() 需要交互模式,并且看起来您没有使用交互模式。我已经更新了我的答案。

标签: python matplotlib plot frequency-distribution


【解决方案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

【讨论】:

  • 你知道如何添加标题吗?
  • ax.set_title('A Title')
  • 你在调用draw之前添加了那行吗?查看我的编辑。
猜你喜欢
  • 2011-08-20
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2017-12-23
  • 1970-01-01
  • 2014-07-15
  • 1970-01-01
相关资源
最近更新 更多