You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python wordcloud库实现双背景色词云?

问题:用Python实现黑灰双背景色词云

我在wordcloud.com用主题生成了黑灰双背景的词云,但用Python的wordcloud库只能做出单一黑色背景的词云。试过黑白、黑白灰蒙版图都没成功,觉得wordcloud本身不支持这个功能,想请教能不能在生成词云后通过imshow或Matplotlib实现双背景色?

我的代码如下:

import numpy as np 
import matplotlib.pyplot as plt
    
from pathlib import Path 
from PIL import Image 
from wordcloud import WordCloud
    
tmp = "some text about Dynasty TV show"
    
alexis_mask = np.array(Image.open('resources/alexis-poster-3.png')) 
print(repr(alexis_mask)) 
alexis_mask[alexis_mask == 0] = 255
    
def color_func(word, font_size, position, orientation, random_state=None,
    **kwargs):
        return "hsl(0, 100%, 27%)"
    
wc = WordCloud(background_color="black", mask=alexis_mask, max_words=500,contour_width=2, contour_color="black")
    
wc.generate(tmp) 
plt.figure(figsize=(28, 20)) 
plt.imshow(wc.recolor(color_func=color_func, random_state=3),interpolation="bilinear") 
plt.imshow(wc)

解决方案

wordcloud库确实不支持直接设置多色背景,但可以通过Matplotlib分层绘制的方式实现:先绘制自定义的黑灰双背景图,再叠加透明背景的词云,就能达到效果。具体步骤如下:

  1. 准备双背景图:创建一个和蒙版尺寸一致的RGB数组,根据需要指定黑、灰区域。可以基于蒙版的形状来划分,比如把蒙版中某类区域设为灰色,其余为黑色。
  2. 生成透明背景的词云:将WordCloud的background_color设为None,并指定mode="RGBA",让词云背景透明,这样下面的双背景能透出来。
  3. 分层绘制:用Matplotlib先绘制双背景图,再绘制词云,最后隐藏坐标轴。

修改后的代码示例:

import numpy as np 
import matplotlib.pyplot as plt
from PIL import Image 
from wordcloud import WordCloud

tmp = "some text about Dynasty TV show"

# 加载并处理蒙版
alexis_mask = np.array(Image.open('resources/alexis-poster-3.png'))
alexis_mask[alexis_mask == 0] = 255

# 1. 创建黑灰双背景图
# 示例:基于蒙版的灰度值划分,把蒙版中小于200的区域设为灰色,其余黑色
background = np.zeros_like(alexis_mask, dtype=np.uint8)
background[alexis_mask < 200] = 128  # 灰色区域
background[alexis_mask >= 200] = 0   # 黑色区域
# 转成RGB格式
background_rgb = np.stack([background, background, background], axis=-1)

# 2. 定义词颜色函数
def color_func(word, font_size, position, orientation, random_state=None,**kwargs):
    return "hsl(0, 100%, 27%)"

# 3. 生成透明背景的词云
wc = WordCloud(
    background_color=None,  # 透明背景
    mode="RGBA",
    mask=alexis_mask, 
    max_words=500,
    contour_width=2, 
    contour_color="black"
)
wc.generate(tmp)
# 重新设置词颜色
wc_colored = wc.recolor(color_func=color_func, random_state=3)

# 4. 分层绘制
plt.figure(figsize=(28, 20))
# 先画双背景
plt.imshow(background_rgb, interpolation="bilinear")
# 再画透明词云
plt.imshow(wc_colored, interpolation="bilinear")
# 隐藏坐标轴
plt.axis("off")
plt.show()

说明

  • 双背景的划分逻辑可以根据你的需求调整,比如替换成基于蒙版的特定区域、自定义形状等。
  • 确保词云的mode="RGBA"和background_color=None,这样词云的非词区域才会透明,不会遮挡下面的双背景。

内容的提问来源于stack exchange,提问作者nettie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 11:37:22