0

I have found many similar questions and tried several suggestions but nothing seems to work. My plot as shown on screen has too much unneeded whitespace around it, while the image file saved with savefig correctly trims it out. This is how it's displayed: enter image description here while the following is the save image file (and what I'd also like being displayed): enter image description here This is my code:

wc = WordCloud(
    width=1920, height=1080, max_words=50, background_color="white"
).generate_from_frequencies(dict(data))

# plot
plt.figure(figsize=(10, 10))
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
fig1 = plt.gcf()  # save the current figure
plt.show()  # because this generates a new picture
fig1.savefig(
    "data/topmentions.png", bbox_inches="tight"
)  # bbox_inches="tight" removes white space around the figure

So the question is: How do I get ris of the white space around the wordcloud when showing it on scree, just like what happens in the saved figure?

Robert Alexander
  • 875
  • 9
  • 24

1 Answers1

1

You can use subplots_adjust to remove margins around your cloud:

wc = WordCloud(
    width=1920, height=1080, max_words=50, background_color="white"
).generate_from_frequencies(dict(data))

# plot
plt.figure(figsize=(10, 10))
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
fig1 = plt.gcf()  # save the current figure
#plt.tight_layout(pad=0)
plt.subplots_adjust(left=0,
                    bottom=0,
                    right=1,
                    top=1)
plt.show()  # because this generates a new picture
fig1.savefig(
    "data/topmentions.png", bbox_inches="tight"
)

Alternatively use plt.tight_layout(pad=0)

Tranbi
  • 11,407
  • 6
  • 16
  • 33