Python wordcloud 周围没有任何空格

Python wordcloud without any whitespaces around the plot

我正在 python3 中使用 wordcloud 模块并尝试保存一个图形,该图形应该只给我 wordcloud 的图像,云周围没有任何空格。我在 stackexchange 中尝试了这里提到的许多滴答声,但它们没有用。下面是我的默认代码,它可以去掉左边和右边的空格,但不能去掉顶部和底部的空格。如果我将 ax = plt.axes([0,0,1,1]) 中的其他两个值也设置为 0,那么我会得到一个空图像。

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)

有人可以帮我解决这个问题吗?

词云是一个图像,即像素数组。 plt.imshow 默认使像素为正方形。这意味着除非图像的宽高比与图形相同,否则顶部和底部或左侧和右侧都会有白色space。

您可以解除固定纵横比设置aspect="auto",

plt.imshow(wc, interpolation="nearest", aspect="auto")

其结果可能是不希望的。

所以你真正想要的是使图形大小适应图像大小。 由于图像是 1500 x 500 像素,您可以选择 100 的 dpi 和 15 x 5 英寸的图形尺寸。

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()


最后使用 matplotlib 可能不是最好的选择。因为你只想保存图像,你可以只使用

from scipy.misc import imsave
imsave(__file__+'.png', wc)