如何按score区间分组,用pandas、Seaborn/Matplotlib生成分组柱状图
问题描述
我有如下DataFrame:
print(df) type score hits 0 good 26 ... 0 1 good 18 ... 0 2 good 47 ... 0 3 bad 9 ... 0 4 good 20 ... 0 ... ... ... ... ... 1701 bad 39 ... 0 1702 good 94 ... 0 1703 good 21 ... 0 1704 good 57 ... 0 1705 good 22 ... 0
希望创建柱状图:将数据按score划分为指定区间(如0-10、11-20等),x轴为区间,y轴为区间内实例数量,同时按type分为两组展示(双组并列柱状图样式)。请问如何用pandas并优先通过Seaborn或Matplotlib实现?
实现步骤
1. 给score划分区间
用pandas的cut函数给score分桶,自定义区间边界:
import pandas as pd # 定义区间边界,示例为0-10、11-20…91-100 bins = range(0, 101, 10) # 生成区间标签,同时设置include_lowest确保0被包含在第一个区间 df['score_bin'] = pd.cut(df['score'], bins=bins, labels=[f'{i+1}-{i+10}' for i in bins[:-1]], include_lowest=True)
2. 统计各区间的type数量
用交叉表快速统计每个区间下不同type的实例数:
# 行是score区间,列是type,值为对应实例数量 count_df = pd.crosstab(df['score_bin'], df['type'])
3. Seaborn实现分组柱状图
Seaborn的barplot适配长格式数据,先将统计结果转成长格式再绘图:
import seaborn as sns import matplotlib.pyplot as plt # 将宽格式转成长格式 melt_df = count_df.reset_index().melt(id_vars='score_bin', var_name='type', value_name='count') # 绘制分组柱状图 sns.barplot(data=melt_df, x='score_bin', y='count', hue='type') plt.xlabel('Score区间') plt.ylabel('实例数量') plt.title('各Score区间不同Type的实例分布') plt.xticks(rotation=45) # 旋转x轴标签避免重叠 plt.show()
4. Matplotlib实现分组柱状图
手动控制柱子位置,实现并列分组效果:
import matplotlib.pyplot as plt import numpy as np # 获取区间标签和type类别 bin_labels = count_df.index.tolist() types = count_df.columns.tolist() x = np.arange(len(bin_labels)) # x轴基础位置 width = 0.35 # 单个柱子宽度 # 绘制两组柱子 fig, ax = plt.subplots() ax.bar(x - width/2, count_df[types[0]], width, label=types[0]) ax.bar(x + width/2, count_df[types[1]], width, label=types[1]) # 设置图表属性 ax.set_xlabel('Score区间') ax.set_ylabel('实例数量') ax.set_title('各Score区间不同Type的实例分布') ax.set_xticks(x, bin_labels) ax.legend() plt.xticks(rotation=45) plt.show()
内容的提问来源于stack exchange,提问作者bigpancakestack
相关产品推荐
相关产品推荐

