2017-06-23 38 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格式存在,因爲這是後端設置的內容。