简体   繁体   中英

How to pass a python wordcloud element to svgwrite method to generate a svg of the wordcloud?

I am trying to generate a svg of the word_cloud being formed out of some hardcoded strings(as of now, later these strings will be dynamically generated). Below is the Python code to generate word_cloud:

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

Now instead of using plt.show(), I want to pass the wordcloud variable to svgwrite method as below:

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

However, this created SVG doesn't contain any wordcloud, only the text (shown in below screenshot): check the screenshot here

Facing some issues using matplotlib (which will use raster graphics in combination with wordcloud although it will be saved as ".svg"), i have figured out another way

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

The embed_font boolean prevented the words from overlapping. Also you have a lot of freedom modifying wordcloud_svg to change colors, fonts , etc. It has an xml-like structure (print it :) )

I found this while looking to do the same exact thing. I got the same results from svgwrite and wound up using matplotlib's features instead.

In matplotlib's documentation there is discussion of changing the format the backend uses. When the backend is using SVG format, the plot can be saved as a .svg

In the imports section:

import matplotlib
matplotlib.use('SVG') #set the backend to SVG
import matplotlib.pyplot as plt

After generating the 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) automatically saves it in SVG format, since that is what the backend is set to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM