1

I want to plot multiple wordclouds to one page, so that I can easily add to a word doc. The following code works, but the wordclouds are too small. How can I fix this? Thank you.

    for t in range(ldamodel.num_topics):

        plt.subplot(6,2,t+1)
        print(ldamodel.show_topic(t, num_words))
        word_p_list = ldamodel.show_topic(t, num_words)
        topic_word_dict = {p[0]:p[1] for p in word_p_list}
        plt.imshow(WordCloud().fit_words(topic_word_dict))
        plt.axis("off")
        plt.title("Topic #" + str(t+1))


    plt.savefig(f"terms_all.png", bbox_inches='tight')
    plt.show()

enter image description here Now it's like this: enter image description here

Victor Wang
  • 765
  • 12
  • 26

1 Answers1

1

Here's a bare-bones implementation that can give you control over the size of the figure. You can adjust the figsize to meet your needs.

rows=6
cols=2

fig, ax = plt.subplots(rows, cols, figsize=(12.5,6.5))

row=0 
col=0 

for t in range(ldamodel.num_topics):
    word_p_list = ldamodel.show_topic(t, num_words)
    topic_word_dict = {p[0]:p[1] for p in word_p_list}
    ax[row][col].imshow(WordCloud().fit_words(topic_word_dict))
    row=row+1
    if row==rows:
        row=0
        col=col+1


plt.savefig(f"terms_all.png", bbox_inches='tight')
plt.show() 
Sameeresque
  • 2,464
  • 1
  • 9
  • 22
  • It's great that I can adjust the size. Almost there. I know very little plotting. How can I take the grid off, add a title for each subplot, and shrink the margin between the two columns? Thanks. – Victor Wang Apr 18 '20 at 04:04
  • Try something like : `ax[row][col].set_title('title')`. Use a tight layout by doing so: `plt.tight_layout()`. To turn off gridlines: `plt.grid(b=None)` – Sameeresque Apr 18 '20 at 04:09
  • I added the title successfully. The grid is still there, and the margin is still quite wide. – Victor Wang Apr 18 '20 at 04:15
  • For better control of the margins you can set your own values:`plt.subplots_adjust(left=0.07, right=0.93, wspace=0.0, hspace=0.0,top=0.94,bottom=0.09)`. Can you update your plot? I'm not quite sure what grid you are talking about. – Sameeresque Apr 18 '20 at 04:16
  • `plt.rcParams["axes.grid"] = False` – Sameeresque Apr 18 '20 at 04:19
  • Weird. The grid is still there. – Victor Wang Apr 18 '20 at 04:23
  • Refer to this [SO](https://stackoverflow.com/questions/45148704/how-to-hide-axes-and-gridlines-in-matplotlib-python) – Sameeresque Apr 18 '20 at 04:26
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/211914/discussion-between-sameeresque-and-victor-wang). – Sameeresque Apr 18 '20 at 04:30
  • 1
    These three lines worked: ax[row][col].set_title("Topic #" + str(t+1)) ax[row][col].grid(False) ax[row][col].axis("off") – Victor Wang Apr 18 '20 at 04:36