0

There is an easy way to generate word frequency plots with NLTK:

my_plot = nltk.FreqDist(some_dynamically_changing_list[0]).plot(20)

some_dynamically_changing_list contains a list of texts that I want to see the word frequency for. The resulting my_plot is an AxesSubplot object. I want to be able to take this object and directly insert it to a dynamically sized subplotted grid. The closest I've gotten to the solution after scouring SO and Google is this. However, I have an issue because I don't want to use plt's plot function. So for example I'd have a dynamic subplot grid:

import matplotlib.pyplot as plt

tot = len(some_dynamically_changing_list)
cols = 5
rows = tot // cols 

if tot % cols != 0:
    rows += 1
    
position = range(1, tot + 1)

fig = plt.figure()
for k in range(tot):
    ax = fig.add_subplot(rows, cols, position[k])

    my_plot = nltk.FreqDist(some_dynamically_changing_list[k]).plot(20)
    ax.plot(my_plot) #This is where I have my issue. 

Of course this won't work, as ax.plot expects data, not a plot. But I want to plug my my_plot into that specific slot. How can I do that (if I can)?

2
  • You can't "take" a subplot and place it somewhere. When creating the plot, it already needs to be on the correct spot. Most functions that create plots allow an ax= parameter, so maybe in this case you could try nltk.FreqDist(...).plot(..., ax=ax)? Further, most such functions create the plot on the "current subplot", which in your case would be already set via fig.add_subplot. Are you sure you are using the latest github version of nltk? Commented Oct 5, 2022 at 15:43
  • Looking into the [source code]((github.com/nltk/nltk/blob/…), nltk's plot doesn't support an ax= parameter, but does use plt.gca() to make sure it draws on the "current ax" (the currently active subplot). Anyway, you should remove ax.plot(my_plot) as such a thing doesn't make sense in matplotlib. Commented Oct 5, 2022 at 15:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.