如何用Seaborn绘制带class分组标签的分数计数直方图
解决嵌套列表DataFrame的分组直方图绘制问题
问题场景
你有如下结构的DataFrame:
name class scores 1 Bob history [13, 14, 11] 2 Chuck math [12, 7, 8] 3 Daren history [26, 14, 9] 4 Elisa english [ 8, 14, 10] 5 Aaron history [12, 13, 23] 6 Tom math [ 7, 7, 28] 7 Dan history [13, 2, 13] 8 Fred english [ 4, 1, 2]
需要绘制直方图:x轴为单个分数值,y轴为分数计数,以class作为分组标签(hue),效果参考Seaborn官方histplot示例的折线式直方图(element="step")。
解决方案
核心是先把嵌套的scores列展开成单行单值的结构,再用Seaborn绘图:
- 展开嵌套列表
用pandas的explode()方法拆分scores列,同时将拆分后的分数转为数值类型(避免后续绘图报错):
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # 初始化你的DataFrame df = pd.DataFrame({ 'name': ['Bob', 'Chuck', 'Daren', 'Elisa', 'Aaron', 'Tom', 'Dan', 'Fred'], 'class': ['history', 'math', 'history', 'english', 'history', 'math', 'history', 'english'], 'scores': [[13,14,11], [12,7,8], [26,14,9], [8,14,10], [12,13,23], [7,7,28], [13,2,13], [4,1,2]] }) # 展开scores列并转换为整数类型 df_exploded = df.explode('scores').astype({'scores': int})
- 绘制分组直方图
用Seaborn的histplot,指定x轴为scores,分组标签为class,并设置element="step"匹配示例效果:
sns.histplot(df_exploded, x='scores', hue='class', element='step') plt.xlabel('分数') plt.ylabel('计数') plt.title('各科目分数分布直方图') plt.show()
说明
explode()是处理列表型列的关键,它会把每个列表元素拆成独立行,保证每个分数都和对应的class绑定,这样Seaborn就能按class分组统计分数的出现次数了。
内容的提问来源于stack exchange,提问作者You_Donut
相关产品推荐
相关产品推荐

