【问题标题】:Python Wordcloud in SVG Vector FormatSVG 矢量格式的 Python Wordcloud
【发布时间】:2021-11-14 16:53:49
【问题描述】:

我正在使用 python wordcloud 库、Wikipedia 和 Matplotlib 生成一些 wordcloud。我的意图是以矢量格式将 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

【问题讨论】:

  • 内容为光栅格式您介意详细说明吗?
  • 内容表示当我用浏览器打开 svg 文件并查看源代码时,我看到“data:image/png;base64”表示实际嵌入在 svg 文件中的 png 文件。
  • 我添加了结果svg,如果你有时间请看一下
  • 请不要将图片上传到Dropbox,而是直接在问题上发布图片
  • 我试过了,但是图片是 svg 格式的。此处不支持上传 svg

标签: python matplotlib svg word-cloud


【解决方案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")

【讨论】:

  • 我尝试了更改但得到了相同的输出。
  • 很抱歉打扰您。我使用了完全相同的功能并得到了一个空白的 svg 文件
  • 你介意发Minimal, Reproducible Example吗?
  • 好的。我正在用我的完整代码更新代码。
  • 我看到你的代码了吗?我是说你的版本
猜你喜欢
  • 2015-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 2016-09-07
相关资源
最近更新 更多