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

如何基于Pandas生成的n-grams频率表绘制频率图与词云

基于n-grams频率DataFrame生成频率图和词云的实现方法

假设你已经通过给定代码生成了包含3-gram频率的DataFrame df,以下是生成频率图和词云的具体实现:

一、生成频率图

我们可以用matplotlib或seaborn绘制条形图,先对DataFrame按频率降序排序,避免图形拥挤:

使用matplotlib实现

import matplotlib.pyplot as plt

# 按频率降序排序,取前10个展示(可根据需求调整数量)
df_sorted = df.sort_values(by='frequency', ascending=False).head(10)

# 设置图形尺寸
plt.figure(figsize=(12, 6))
# 绘制条形图
plt.bar(df_sorted.index, df_sorted['frequency'])
# 旋转x轴标签,避免文字重叠
plt.xticks(rotation=45, ha='right')
# 添加标题与轴标签
plt.title('Top 10 3-gram频率分布')
plt.xlabel('3-gram词组')
plt.ylabel('出现频率')
# 自动调整布局
plt.tight_layout()
# 显示图形
plt.show()

使用seaborn实现

import seaborn as sns

plt.figure(figsize=(12, 6))
sns.barplot(x=df_sorted.index, y=df_sorted['frequency'])
plt.xticks(rotation=45, ha='right')
plt.title('Top 10 3-gram频率分布')
plt.xlabel('3-gram词组')
plt.ylabel('出现频率')
plt.tight_layout()
plt.show()

二、生成词云

需要先安装wordcloud库(执行pip install wordcloud),再将DataFrame转换为字典格式传入词云生成器:

from wordcloud import WordCloud

# 将DataFrame转换为{词组: 频率}的字典格式
ngram_freq_dict = df.to_dict()['frequency']

# 初始化词云对象,配置参数
wordcloud = WordCloud(
    width=800,
    height=400,
    background_color='white',
    max_words=50,  # 最多展示50个词组
    collocations=False  # 避免拆分原3-gram词组
)

# 基于频率生成词云
wordcloud.generate_from_frequencies(ngram_freq_dict)

# 展示词云
plt.figure(figsize=(12, 6))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')  # 隐藏坐标轴
plt.title('3-gram词云')
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:45:34