Reputation: 329
I am working with wordcloud module in python3 and trying to save a figure that should only give me the image of the wordcloud without any whitespaces around the cloud. I tried many ticks mentioned here in stackexchange but they didn't work. Below is my default code, which can get rid of the whitespace on the left and right but not on the top and bottom. If I make the other two values in ax = plt.axes([0,0,1,1]) to 0 as well then I get an empty image.
wordcloud = WordCloud(font_path=None, width = 1500, height=500,
max_words=200, stopwords=None, background_color='whitesmoke', max_font_size=None, font_step=1, mode='RGB',
collocations=True, colormap=None, normalize_plurals=True).generate(filteredText)
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes([0,0,1,1])
plt.imshow(wordcloud, interpolation="nearest")
plt.axis('off')
plt.savefig('fig.png', figsize = (1500,500), dpi=300)
Could someone please help me out with this?
Upvotes: 4
Views: 3235
Reputation: 339250
The wordcloud is an image, i.e. an array of pixels. plt.imshow
makes pixels square by default. This means that unless the image has the same aspect ratio than the figure, there will be white space either the top and bottom, or the left and right side.
You can free the fixed aspect ratio setting aspect="auto"
,
plt.imshow(wc, interpolation="nearest", aspect="auto")
the result of which is probably undesired.
So what you would really want is to adapt the figure size to the image size. Since the image is 1500 x 500 pixels, you may choose a dpi of 100 and a figure size of 15 x 5 inch.
wc = wordcloud.WordCloud(font_path=None, width = 1500, height=500,
max_words=200, stopwords=None, background_color='whitesmoke', max_font_size=None, font_step=1, mode='RGB',
collocations=True, colormap=None, normalize_plurals=True).generate(text)
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(15,5), dpi=100)
ax = plt.axes([0,0,1,1])
plt.imshow(wc, interpolation="nearest", aspect="equal")
plt.axis('off')
plt.savefig(__file__+'.png', figsize=(15,5), dpi=100)
plt.show()
from scipy.misc import imsave
imsave(__file__+'.png', wc)
Upvotes: 7