42

我正在使用带有一些 txt 文件的词云。如果我想 1) 提高分辨率和 2) 删除空边框,我该如何更改此示例。

#!/usr/bin/env python2
"""
Minimal Example
===============
Generating a square wordcloud from the US constitution using default arguments.
"""

from os import path
import matplotlib.pyplot as plt
from wordcloud import WordCloud

d = path.dirname(__file__)

# Read the whole text.
text = open(path.join(d, 'constitution.txt')).read()
wordcloud = WordCloud().generate(text)
# Open a plot of the generated image.
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
4

4 回答 4

91

您无法增加图像的分辨率plt.show(),因为这是由您的屏幕决定的,但您可以增加尺寸。这允许它在不模糊的情况下进行缩放、缩放等。为此,将尺寸传递给WordCloud,例如

wordcloud = WordCloud(width=800, height=400).generate(text)

然而,这仅仅决定了创建的图像的大小WordCloud。当您使用matplotlib它显示它时,它会缩放到绘图画布的大小,(默认情况下)大约为 800x600,并且您再次失去质量。要解决此问题,您需要在调用之前指定图形的大小imshow,例如

plt.figure( figsize=(20,10) )
plt.imshow(wordcloud)

通过这样做,我可以成功创建一个 2000x1000 的高分辨率词云。

对于您的第二个问题(删除边框),首先我们可以将边框设置为黑色,因此不太明显,例如

plt.figure( figsize=(20,10), facecolor='k' )

您还可以通过使用来缩小边框的大小tight_layout,例如

plt.tight_layout(pad=0)

最终代码:

# Read the whole text.
text = open(path.join(d, 'constitution.txt')).read()
wordcloud = WordCloud(width=1600, height=800).generate(text)
# Open a plot of the generated image.

plt.figure( figsize=(20,10), facecolor='k')
plt.imshow(wordcloud)
plt.axis("off")
plt.tight_layout(pad=0)
plt.show()

通过将最后两行替换为以下内容,您可以获得如下所示的最终输出:

plt.savefig('wordcloud.png', facecolor='k', bbox_inches='tight')

最终宪法 wordcloud

于 2015-03-01T15:53:10.603 回答
3

如果您尝试使用图像作为遮罩,请确保使用大图像以获得更好的图像质量。我花了几个小时弄清楚这一点。

这是我使用的代码片段的示例

mask = np.array(Image.open('path_to_your_image'))
image_colors = ImageColorGenerator(mask)
wordcloud = WordCloud(width=1600, height=800, background_color="rgba(255, 255, 255, 0)", mask=mask
                     ,color_func = image_colors).generate_from_frequencies(x)

# Display the generated image:
plt.figure( figsize=(20,10) )
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
于 2019-10-25T08:17:58.477 回答
0

它非常简单,plt.tight_layout(pad=0)可以完成这项工作,减少背景空间,去除多余的填充。

于 2019-11-19T12:17:25.343 回答
-3

模糊的词云——我一直在为此苦苦挣扎。就我的使用而言,我发现出现频率最高的单词和出现次数很少的单词之间的差异太大,导致计数较低的单词无法阅读。当我缩放更频繁的计数以减少差异时,所有低频词都更具可读性。

于 2016-10-18T22:04:05.223 回答