2017-06-23 81 views
1

我想生成一个由一些硬编码字符串组成的word_cloud的svg(截至目前,以后这些字符串将被动态生成)。 下面是Python代码生成word_cloud:如何将python wordcloud元素传递给svgwrite方法以生成wordcloud的svg?

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不包含任何wordcloud,只有文本(如下图所示): check the screenshot here

回答

0

我发现这一点,而寻找做同样的事情。我从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(文件名)自动保存后它以SVG格式存在,因为这是后端设置的内容。