I am generating some wordclouds using python wordcloud library, Wikipedia and Matplotlib. My intention is to save the wordcloud in SVG file in vector format. Currently the program is saving the file in SVG format but the contents are in raster format. Part of my codes are as follows:
# Import packages
import wikipedia
import re
from wordcloud import WordCloud, STOPWORDS
import matplotlib
matplotlib.use('SVG') #set the backend to SVG
import matplotlib.pyplot as plt
# Specify the title of the Wikipedia page
wiki = wikipedia.page('Puzzle')
# Extract the plain text content of the page
text = wiki.content
# Clean text
text = re.sub(r'==.*?== ', '', text)
text = text.replace('\n', '')
# Define a function to plot word cloud
def plot_cloud(wordcloud):
fname = "cloud_test"
plt.axis("off")
fig = plt.gcf() #get current figure
fig.set_size_inches(10,10)
plt.savefig(fname ".svg", dpi=700, format="svg")
plt.imshow(wordcloud, interpolation="bilinear")
# Generate word cloud
wordcloud = WordCloud(width = 3000, height = 2000, random_state=1, background_color='black', colormap='Pastel1', collocations=False, stopwords = STOPWORDS).generate(text)
# Plot
plot_cloud(wordcloud)
Here is the result: https://www.dropbox.com/s/a2ux72dtq62atkd/cloud_test.svg?dl=1
CodePudding user response:
To save your figure you can use:
plt.savefig(fname, dpi=700)
to plt.savefig(fname ".svg", dpi=700, format="svg")
Remember to call this before plt.show()
Your function should look like
def plot_cloud(wordcloud):
fname = "cloud_test"
plt.axis("off")
fig = plt.gcf() #get current figure
fig.set_size_inches(10,10)
plt.savefig(fname ".svg", dpi=700, format="svg")
plt.imshow(wordcloud, interpolation="bilinear")