Tuma
Tuma

Reputation: 817

How to save an SVG string to file in python

I'm using this wordcloud generator to do as the name suggests, and would like to save the contents as .svg. The library has a to_svg() function, which returns a string. It also has a to_file() which doesn't save in this format.

Is there any way to use pyplot's savefig function to save the string output from to_svg() to a file?

Upvotes: 1

Views: 3069

Answers (1)

Grismar
Grismar

Reputation: 31354

It doesn't use pyplot.savefig, but it needs nothing beyond the wordcloud library you linked and Python itself:

from wordcloud import WordCloud

wc = WordCloud()
wc.generate_from_text('This is a word cloud example which has a few words, showing them word for word in a cloud.')

svg_text = wc.to_svg()
with open('my.svg', 'w') as f:
    f.write(svg_text)

The output is the word cloud .svg you're after.

this is a screengrab from the .svg in InkScape

Upvotes: 4

Related Questions