【问题标题】:Python wordcloud without any whitespaces around the plotPython wordcloud 图周围没有任何空格
【发布时间】:2017-10-28 01:57:54
【问题描述】:

我正在使用 python3 中的 wordcloud 模块并尝试保存一个应该只给我 wordcloud 的图像而云周围没有任何空格的图形。我尝试了 stackexchange 中提到的许多滴答声,但没有奏效。下面是我的默认代码,它可以去掉左右两边的空格,但不能去掉顶部和底部的空格。如果我将 ax = plt.axes([0,0,1,1]) 中的其他两个值也设为 0,那么我会得到一个空图像。

wordcloud = WordCloud(font_path=None, width = 1500, height=500,  
            max_words=200,  stopwords=None, background_color='whitesmoke', max_font_size=None, font_step=1, mode='RGB', 
            collocations=True, colormap=None, normalize_plurals=True).generate(filteredText)

import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes([0,0,1,1])
plt.imshow(wordcloud, interpolation="nearest")
plt.axis('off')
plt.savefig('fig.png', figsize = (1500,500), dpi=300)

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: python matplotlib word-cloud


    【解决方案1】:

    wordcloud 是一个图像,即一个像素数组。 plt.imshow 默认使像素为正方形。这意味着除非图像与图形具有相同的纵横比,否则顶部和底部或左侧和右侧都会有空白。

    您可以释放固定纵横比设置aspect="auto"

    plt.imshow(wc, interpolation="nearest", aspect="auto")
    

    结果可能是不希望的。

    因此,您真正想要的是使图形大小适应图像大小。 由于图像为 1500 x 500 像素,您可以选择 100 的 dpi 和 15 x 5 英寸的图形尺寸。

    wc = wordcloud.WordCloud(font_path=None, width = 1500, height=500,  
                max_words=200,  stopwords=None, background_color='whitesmoke', max_font_size=None, font_step=1, mode='RGB', 
                collocations=True, colormap=None, normalize_plurals=True).generate(text)
    
    import matplotlib.pyplot as plt
    
    fig = plt.figure(figsize=(15,5), dpi=100)
    ax = plt.axes([0,0,1,1])
    plt.imshow(wc, interpolation="nearest", aspect="equal")
    plt.axis('off')
    plt.savefig(__file__+'.png', figsize=(15,5), dpi=100)
    plt.show()
    


    最后使用 matplotlib 可能不是最好的选择。由于您只想保存图像,因此您可以使用
    from scipy.misc import imsave
    imsave(__file__+'.png', wc)
    

    【讨论】:

    • 非常感谢@ImportanceOfBeingErnest 这正是我想要的一切。我现在使用 from scipy.misc import imsave imsave(__file__+'.png', wc) ,它工作得很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 2014-04-01
    • 2017-08-27
    • 2017-05-23
    相关资源
    最近更新 更多