用词云提高分辨率并去除空边框 [英] Increase resolution with word-cloud and remove empty border

查看:85
本文介绍了用词云提高分辨率并去除空边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 word cloud 和一些 txt 文件.如果我想 1) 增加,我该如何更改 这个示例分辨率和2)删除空白边框.

I am using word cloud with some txt files. How do I change this example if I wanted to 1) increase resolution and 2) remove empty border.

#!/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()

推荐答案

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

You can't increase the resolution of the image in plt.show() since that is determined by your screen, but you can increase the size. This allows it to scale, zoom, etc. without blurring. To do this pass dimensions to WordCloud, e.g.

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

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

However, this just determines the size of the image created by WordCloud. When you display this using matplotlib it is scaled to the size of the plot canvas, which is (by default) around 800x600 and you again lose quality. To fix this you need to specify the size of the figure before you call imshow, e.g.

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

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

By doing this I can successfully create a 2000x1000 high resolution word cloud.

对于您的第二个问题(去除边框),首先我们可以将边框设置为黑色,这样它就不那么明显了,例如

For your second question (removing the border) first we could set the border to black, so it is less apparent, e.g.

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

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

You can also shrink the size of the border by using tight_layout, e.g.

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

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

By replacing the last two lines with the following you can get the final output shown below:

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

这篇关于用词云提高分辨率并去除空边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆