You need to enable JavaScript to run this app. 如何使用Python绘制多数值列均值的分组柱状图
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python绘制多数值列均值的分组柱状图

可行实现方案

方案1:转换数据格式后使用seaborn catplot

你遇到的限制本质是因为你的数据集是宽格式,数值列以独立字段存在,无法直接作为分类变量传入hue。只需先把宽格式转为长格式,即可直接使用catplot实现需求:

  • 第一步:用pandas的melt方法完成格式转换
    假设原始数据存在DataFrame变量df中,转换代码如下:
    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    # 宽表转长表
    long_df = df.melt(
        id_vars="category",
        value_vars=["sales", "profit", "此处替换为剩余4个数值列的列名"],
        var_name="metrics",
        value_name="value"
    )
    
    转换后得到3列的长表:category为原分类列,metrics为数值列的名称(如sales、profit),value为对应数值,此时metrics就是标准的分类变量。
  • 第二步:绘制分组柱状图
    直接把metrics传入hue参数即可,catplot的柱状图默认会自动计算每组均值:
    sns.catplot(
        data=long_df,
        x="category",
        y="value",
        hue="metrics",
        kind="bar",
        ci=None # 不需要显示置信区间可保留该行,否则删掉即可
    )
    plt.show()
    
    如果你需要提前手动聚合均值,也可以先做分组计算再传入:
    # 提前计算均值
    mean_df = long_df.groupby(["category", "metrics"], as_index=False)["value"].mean()
    # 绘图
    sns.catplot(data=mean_df, x="category", y="value", hue="metrics", kind="bar")
    plt.show()
    

方案2:无需转换格式,直接用matplotlib原生绘制

如果你不想修改数据格式,也可以手动计算均值后用matplotlib原生实现,代码如下:

import numpy as np
import matplotlib.pyplot as plt

# 计算每个category下各数值列的均值
mean_df = df.groupby("category").mean()
# 定义绘图参数
x = np.arange(len(mean_df.index)) # 7个分类的基准x坐标
width = 0.12 # 单根柱子宽度,6个数值列总宽度为0.72,不会重叠
metrics_cols = ["sales", "profit", "此处替换为剩余4个数值列的列名"]

# 循环绘制每个数值列的柱子
for idx, col in enumerate(metrics_cols):
    plt.bar(x + idx*width, mean_df[col], width=width, label=col)

# 配置坐标轴与图例
plt.xticks(x + width*2.5, mean_df.index)
plt.xlabel("category")
plt.ylabel("均值")
plt.legend()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 22:00:04