我正在尝试生成由一些硬编码字符串组成的word_cloud的svg (到目前为止,这些字符串将在稍后动态生成)。下面是生成word_cloud的Python代码:
from os import path
from wordcloud import WordCloud
d = path.dirname(__file__)
# Read the whole text.
#text = open(path.join(d, 'test.txt')).read()
mytext = ['hello, hi, ibm, pune, hola']
# Generate a word cloud image
wordcloud = WordCloud().generate(text)
import svgwrite
# Display the generated image:
# the matplotlib way:
import matplotlib.pyplot as plt
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")现在,我不使用plt.show(),而是将wordcloud变量传递给svgwrite方法,如下所示:
svg_document = svgwrite.Drawing(filename = "test-svgwrite.svg",profile = 'full')
svg_document.add(svg_document.text(wordcloud,
insert = (210, 110)))
svg_document.tostring()
svg_document.save()然而,这个创建的SVG不包含任何词云,只包含文本(如下面的截图所示):check the screenshot here
发布于 2020-10-01 22:10:23
面对使用matplotlib的一些问题(它将结合使用栅格图形和wordcloud,尽管它将被保存为".svg"),我想出了另一种方法
wordcloud = WordCloud()
wordcloud.generate_from_frequencies(frequencies=features)
wordcloud_svg = wordcloud.to_svg(embed_font=True)
f = open("filename.svg","w+")
f.write(wordcloud_svg )
f.close()embed_font布尔值防止了单词重叠。您还可以很自由地修改wordcloud_svg以更改颜色、字体等。
发布于 2017-08-07 04:21:38
我在做同样的事情时发现了这一点。我从svgwrite得到了相同的结果,并最终使用matplotlib的功能。
在matplotlib的documentation中,有关于改变后端使用的格式的讨论。后端使用SVG格式时,可以将绘图另存为.svg
在导入部分中:
import matplotlib
matplotlib.use('SVG') #set the backend to SVG
import matplotlib.pyplot as plt在生成WordCloud之后
fname = "cloud_test"
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
fig = plt.gcf() #get current figure
fig.set_size_inches(10,10)
plt.savefig(fname, dpi=700)savefig(filename)自动将其保存为SVG格式,因为这是后端设置的格式。
https://stackoverflow.com/questions/44715044
复制相似问题