Python画词云图,Python画圆形词云图,API详解

在 Python 中,词云图的常用库是 wordcloud。以下是核心 API 参数的详细讲解,以及一个完整的使用示例。

一、参数 类型 默认值 说明

参数 类型 默认值 说明
width int 400 词云图的宽度(像素)
height int 200 词云图的高度(像素)
background_color str “black” 背景颜色,可以是颜色名称(如 “white”)或十六进制值(如 “#FFFFFF”)
colormap str / matplotlib colormap “viridis” 配色方案,例如 “Blues”, “Reds”, “Greens” 等
font_path str 字体文件路径(支持中文需指定中文字体,如 font_path=‘msyh.ttc’)
max_words int 200 最多显示的词汇数量
stopwords set / dict - 停用词集合,可以是预定义的集合或自定义字典
mask ndarray / None - 使用图片形状作为词云图的蒙版(需配合 numpy 和 PIL 库)
contour_width int 0 蒙版轮廓的宽度(仅当 mask 非空时有效)
contour_color str “black” 蒙版轮廓的颜色
collocations bool True 是否包含词语搭配(如 “New York”)
prefer_horizontal float 0.9 词汇水平排列的偏好(0~1,值越大越倾向于水平排列)
scale float 1 词云图的分辨率缩放比例
min_font_size int 4 词汇的最小字体大小
max_font_size int - 词汇的最大字体大小(默认根据词频自动调整)
random_state int / None - 随机种子,用于控制词云图的生成随机性

二. 完整使用示例

以下是一个生成词云图的完整代码示例,包含主要参数的用法:

from wordcloud import WordCloud, ImageColorGenerator
import matplotlib.pyplot as plt


file_name = '一段文本.txt'
# 打开文件
with open(file_name, 'r', encoding='utf-8') as file:
    # 读取文件内容
    text = file.read()

# 生成词云并使用图片颜色
wordcloud = WordCloud(
    background_color='white',
    max_words=100,
    width=800, height=400
).generate(text)


plt.figure(figsize=(10, 5))
plt.imshow(wordcloud)
plt.axis("off")
plt.savefig('词云图2.png')
plt.show()

Python画词云图,Python画圆形词云图,API详解_第1张图片
由于wordcloud库默认不支持中文,需要指定一个支持中文的字体。你可以使用Mac系统中已有的中文字体,如“SimHei”。首先,你需要找到这个字体的路径。

在终端中运行以下命令来查找系统中可用的字体:

fc-list :lang=zh

Python画词云图,Python画圆形词云图,API详解_第2张图片

from wordcloud import WordCloud, ImageColorGenerator
import matplotlib.pyplot as plt

file_name = '词频数据.txt'
# 打开文件
with open(file_name, 'r', encoding='utf-8') as file:
    # 读取文件内容
    text = file.read()

# 生成词云并使用图片颜色
wordcloud = WordCloud(
    font_path="/System/Library/Fonts/STHeiti Medium.ttc",
    background_color='white',
    max_words=100,
    width=800, height=400
).generate(text)


plt.figure(figsize=(10, 5))
plt.imshow(wordcloud)
plt.axis("off")
plt.savefig('词云图2.png')
plt.show()

Python画词云图,Python画圆形词云图,API详解_第3张图片


三、高级用法,使用图片蒙版

from wordcloud import WordCloud, ImageColorGenerator
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import pandas as pd

# 自定义一个圆形的蒙版mask
size = (1000, 1000)
mask = np.ones(size, dtype=np.uint8) * 0  # 先全白
center = (size[0] // 2, size[1] // 2)
radius = min(center) - 20  # 缩小半径,留中间白边
y, x = np.ogrid[:size[0], :size[1]]
mask[(x - center[0])**2 + (y - center[1])**2 > radius**2] = 255  # 外围变黑
Image.fromarray(mask).save("correct_circle_mask.png")  # 保存正确mask

file_name = '一段文本.txt'
# 打开文件
with open(file_name, 'r', encoding='utf-8') as file:
    # 读取文件内容
    text = file.read()

mask = np.array(Image.open("correct_circle_mask.png"))  # 替换为你的mask路径

# 生成词云并使用图片颜色
wordcloud = WordCloud(
    # font_path="simhei.ttf",
    background_color='white',
    mask=mask,
    # color_func=ImageColorGenerator(mask),  # 使用mask颜色
    max_words=100,
    width=1000, height=1000,        # 与mask尺寸一致
).generate(text)


plt.figure(figsize=(10, 5))
plt.imshow(wordcloud)
plt.axis("off")
plt.savefig('词云图.png')
plt.show()

Python画词云图,Python画圆形词云图,API详解_第4张图片


四、多子图


from wordcloud import WordCloud, ImageColorGenerator
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import pandas as pd

size = (600, 600)
mask = np.ones(size, dtype=np.uint8) * 0  # 先全白
center = (size[0] // 2, size[1] // 2)
radius = min(center) - 20  # 缩小半径,留中间白边
y, x = np.ogrid[:size[0], :size[1]]
mask[(x - center[0])**2 + (y - center[1])**2 > radius**2] = 255  # 外围变黑
Image.fromarray(mask).save("correct_circle_mask.png")  # 保存正确mask


# 创建一个 2x2 的子图布局
fig, axes = plt.subplots(2, 3, figsize=(15, 8))


title = [2000,2005,2010,2015,2020,2025]

# 遍历每个子图并生成词云
for i,ax in enumerate(axes.flatten()):
    # 读取文件内容
    file_name = f'水利数据/词频数据_{title[i]}.txt'
    with open(file_name, 'r', encoding='utf-8') as file:
        text = file.read()

    # 生成词云
    wordcloud = WordCloud(
    font_path="/System/Library/Fonts/STHeiti Medium.ttc", # mac 和windows不一样
    background_color='white',
    colormap='viridis', # “viridis”	配色方案,例如 “Blues”, “Reds”, “Greens” 等
    max_words=100,
    width=600, height=600,
    # prefer_horizontal=0.9, # 词汇水平排列的偏好(0~1,值越大越倾向于水平排列)默认0.9
    mask=mask,
    min_font_size = 18
    ).generate(text)

    # 在子图中显示词云
    ax.imshow(wordcloud, interpolation='bilinear')
    ax.axis('off')
    ax.set_title(title[i],  fontsize=18,loc='left', pad=6)

# 生成词云并使用图片颜色
# 调整子图之间的间距
plt.tight_layout()

plt.savefig('水利行业热门词云图2.png')
plt.show()

Python画词云图,Python画圆形词云图,API详解_第5张图片

五、自定义停用词

就是这些词语不会显示,比如一句话中 的、地、我、他、is this

# 从文件加载停用词
with open("stopwords.txt", "r", encoding="utf-8") as f:
    stopwords = set(f.read().splitlines())
 
wordcloud = WordCloud(stopwords=stopwords).generate(text)

六、 注意事项

中文字体:如果要生成中文词云,必须指定中文字体文件(如 font_path=‘msyh.ttc’)。
停用词:可以通过 stopwords 参数排除无意义的词汇(如 “的”, “是”, “在”)。
性能优化:对于大规模文本,可以先进行分词和词频统计,再使用 generate_from_frequencies 方法。

你可能感兴趣的:(python,开发语言)