一、词云支持的 所有核心效果
你只需要改下面这些参数,就能做出完全不同的词云:
1. 形状效果
- 方形(默认)
- 圆形
- 任意图片形状(蒙版)
- 心形、星星、动物等
2. 颜色效果
- 纯色背景
- 图片取色
- 随机彩色
- 黑底、白底、透明底
3. 字体效果
- 任意字体(黑体、宋体、楷体、圆体)
- 字体大小
- 字体粗细
4. 排版效果
- 横排
- 竖排
- 密集 / 松散
- 旋转文字
5. 高级效果
- 轮廓边
- 最大词数
- 停用词(过滤不想显示的词)
二、直接给你 5 种最常用好看风格代码
复制就能跑!
风格 1:标准彩色词云(最常用)
python
运行
from wordcloud import WordCloud
text = "Python 好玩 编程 爬虫 自动化 有趣 学习"
wc = WordCloud(
width=600,
height=400,
background_color="white", # 背景色
font_path="simhei.ttf", # 中文必须加
colormap="viridis", # 配色方案
)
wc.generate(text)
wc.to_file("wordcloud.png")
风格 2:黑色背景 + 炫酷配色
python
运行
wc = WordCloud(
width=600, height=400,
background_color="black",
font_path="simhei.ttf",
colormap="plasma" # 炫酷紫蓝渐变
)
风格 3:圆形词云
python
运行
python
import numpy as np
from PIL import Image, ImageDraw
from wordcloud import WordCloud
# ===================== 自动生成圆形蒙版(不需要图片!)=====================
width = 800
height = 800
mask = Image.new('L', (width, height), 255) # 白色背景
draw = ImageDraw.Draw(mask)
draw.ellipse((50, 50, width-50, height-50), fill=0) # 画黑色圆形
mask = np.array(mask)
# ========================================================================
text = "Python 好玩 编程 爬虫 自动化 有趣 学习"
wc = WordCloud(
mask=mask, # 使用自动生成的圆形
background_color="white", # 背景白色
font_path="msyh.ttc", # 微软雅黑(Windows 自带,最清晰)
colormap="hsv", # 彩虹彩色(超好看)
contour_width=2, # 圆形边框宽度
contour_color="blue" # 边框颜色
)
wc.generate(text)
wc.to_file("circle_wordcloud.png")
import os
os.system("circle_wordcloud.png")
print("✅ 圆形词云已生成:circle_wordcloud.png")
风格 4:心形词云
python
运行
python
from wordcloud import WordCloud
import numpy as np
from PIL import Image, ImageDraw
# ===================== 自动生成心形蒙版(不需要图片!)=====================
width, height = 800, 800
mask = Image.new('L', (width, height), 255)
draw = ImageDraw.Draw(mask)
# 画一个完美心形
draw.ellipse((200, 100, 600, 500), fill=0)
draw.ellipse((100, 100, 500, 500), fill=0)
draw.polygon((100, 300, 400, 700, 700, 300), fill=0)
mask = np.array(mask)
# ========================================================================
# 你的关键词
text = "Python 好玩 编程 爬虫 自动化 有趣 学习 AI 数据分析 代码 零基础"
# 生成心形词云
wc = WordCloud(
mask=mask,
background_color="black",
font_path="msyh.ttc", # 微软雅黑(Windows自带)
colormap="hsv", # 彩虹炫彩
contour_width=3, # 心形边框粗细
contour_color="red", # 边框颜色
max_words=100,
prefer_horizontal=0.6
)
wc.generate(text)
wc.to_file("2.png")
import os
os.system("2.png")
print("✅ 完美心形词云已生成!")
风格 5:文字随机旋转(更活泼)
python
运行
wc = WordCloud(
width=600, height=400,
font_path="simhei.ttf",
random_state=42, # 随机颜色
rotate_ratio=0.5 # 50% 文字旋转
)
三、超全 配色表 colormap
直接替换 colormap="..." 就能换风格:
viridis蓝绿plasma紫粉inferno黑红magma紫红cividis黄蓝rainbow彩虹ocean海洋spring春天summer夏天autumn秋天winter冬天
四、你原来的代码 → 升级成 炫酷版
python
运行
from wordcloud import WordCloud
text = "Python 好玩 编程 爬虫 自动化 有趣 学习"
wc = WordCloud(
width=800,
height=600,
background_color="black",
font_path="simhei.ttf",
colormap="rainbow", # 彩虹色
max_words=50, # 最多显示词数
rotate_ratio=0.3 # 轻微旋转更好看
)
wc.generate(text)
wc.to_file("wordcloud.png")
print("词云已保存")