0

I'm pretty new to python, so I am working through the nltk book. I am also trying to become familiar with manipulating graphs and plots. I plotted a conditional frequency distribution, and I would like to start by removing the top and left spines. This is what I have:

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)

I get the following error:

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

Is there any way to manipulate a conditonal frequency distribution? Thank you!

enter image description here

user3528925
  • 209
  • 1
  • 2
  • 9
  • Are deleting your comments? The problem you are having is because interactive mode is required to use draw() and it looks like you aren't using interactive mode. I've updated my answer. – Molly May 19 '14 at 23:31

1 Answers1

1

The spines aren't an element of the conditional frequency distribution, they are an element of the axes on which the conditional frequency distribution is plotted. You can can access them by assigning a variable to the axes. There's an example below and another example here.

There is an additional complication. cfd.plot() calls plt.show which displays the figure immediately. In order to update it after this you need to be in interactive mode. Depending on the backend that you are using, you may be able to turn interactive mode with plt.ion(). The example below will work with MacOSX, Qt4Agg, and possibly others but I didn't test it. You can find out what backend you are using with 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

Molly
  • 13,240
  • 4
  • 44
  • 45