我在一些txt文件中使用字云。如果我想提高分辨率和删除空边框,如何更改这个例子。
#!/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()
发布于 2015-03-01 07:53:10
您不能提高plt.show()
中图像的分辨率,因为这是由屏幕决定的,但是可以增加大小。这使得它可以缩放、缩放等,而不会模糊。若要将维度传递给WordCloud
,请执行以下操作。
wordcloud = WordCloud(width=800, height=400).generate(text)
但是,这只是确定由WordCloud
创建的映像的大小。当您使用matplotlib
显示它时,它会缩放到绘图画布的大小,这个大小(默认情况下)在800x600左右,您将再次失去质量。要解决这个问题,您需要在调用imshow
之前指定图形的大小。
plt.figure( figsize=(20,10) )
plt.imshow(wordcloud)
通过这样做,我可以成功地创建一个2000x1000高分辨率的word云。
对于你的第二个问题(移除边框),首先我们可以把边框设置为黑色,所以不那么明显。
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')
发布于 2019-10-25 00:17:58
如果你试图使用一个图像作为一个面具,确保使用一个大的图像,以获得更好的图像质量。我花了好几个小时才弄明白的。
下面是我使用的一个代码片段的示例
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-11-19 04:17:25
它非常简单,plt.tight_layout(pad=0)
做的工作,减少了空间的背景,消除多余的填充。
https://stackoverflow.com/questions/28786534
复制相似问题