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

如何用简洁语法绘制DataFrame的barplot?

优化分组柱状图(Barplot)代码的方案

以下是针对冗长重复的Barplot代码的几种高效优化思路,核心是减少手动复制、利用库的内置功能批量处理:

方案1:转长表后用Seaborn一键绘制

如果你的DataFrame是宽格式(每个分组对应一列),先通过melt转成长格式,再用Seaborn的barplot自动处理分组、颜色和图例,彻底避免重复绘制代码。

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

# 将宽表转为长格式(适配Seaborn的分组绘图逻辑)
df_long = df.melt(
    var_name="分组名称",
    value_name="数值",
    ignore_index=False
).reset_index().rename(columns={"index": "类别"})

# 一键绘制分组柱状图
plt.figure(figsize=(10, 6))
sns.barplot(
    data=df_long,
    x="类别",
    y="数值",
    hue="分组名称",
    palette="Set2"  # 可自定义配色
)
plt.title("分组柱状图")
plt.xlabel("类别")
plt.ylabel("数值")
plt.legend(title="分组")
plt.show()

方案2:用循环批量绘制柱子

如果不想转换表结构,可通过循环遍历DataFrame的列,自动计算每个分组柱子的位置偏移,替代手动重复编写plt.bar。

import matplotlib.pyplot as plt
import numpy as np

bar_width = 0.2  # 单个柱子宽度
x = np.arange(len(df.index))  # x轴类别的位置基准

plt.figure(figsize=(10, 6))
# 循环遍历所有分组列,批量绘制柱子
for idx, col_name in enumerate(df.columns):
    plt.bar(
        x + idx * bar_width,  # 自动计算柱子偏移位置
        df[col_name],
        width=bar_width,
        label=col_name
    )

# 调整x轴标签位置,使其对齐分组中间
plt.xticks(x + bar_width*(len(df.columns)-1)/2, df.index)
plt.title("分组柱状图")
plt.xlabel("类别")
plt.ylabel("数值")
plt.legend()
plt.show()

方案3:封装为可复用函数

如果需要多次绘制类似的柱状图,可将绘图逻辑封装成函数,后续只需传入DataFrame和参数即可,彻底消除重复代码。

import matplotlib.pyplot as plt
import numpy as np

def plot_grouped_bar(
    df,
    bar_width=0.2,
    figsize=(10, 6),
    title="分组柱状图",
    xlabel="类别",
    ylabel="数值"
):
    x = np.arange(len(df.index))
    plt.figure(figsize=figsize)
    for idx, col_name in enumerate(df.columns):
        plt.bar(x + idx * bar_width, df[col_name], width=bar_width, label=col_name)
    plt.xticks(x + bar_width*(len(df.columns)-1)/2, df.index)
    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.legend()
    plt.show()

# 调用示例
plot_grouped_bar(df, bar_width=0.18, title="自定义标题")

核心优化要点

  • 消除重复代码:用循环/长表转换替代手动复制plt.bar
  • 自动计算位置:借助numpy自动处理分组柱子的偏移,避免手动硬编码坐标
  • 利用库的内置能力:Seaborn/Pandas Plot都支持直接处理分组数据,减少手动配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 20:40:18