Python SVG 矢量格式的文字云

Python Wordcloud in SVG Vector Format

我正在使用 python 词云库、维基百科和 Matplotlib 生成一些词云。我的目的是以矢量格式将 wordcloud 保存在 SVG 文件中。目前该程序正在以 SVG 格式保存文件,但内容是光栅格式。我的部分代码如下:

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

结果如下: https://www.dropbox.com/s/a2ux72dtq62atkd/cloud_test.svg?dl=1

要保存您的身材,您可以使用:

plt.savefig(fname, dpi=700)plt.savefig(fname + ".svg", dpi=700, format="svg")

记得在plt.show()

之前调用这个

您的函数应该如下所示

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