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

如何基于多列组合为x轴的DataFrame绘制分组柱状图

实现三列组合为x轴的分组柱状图方法

你可以通过两种方式实现需求,分别如下:

方式1:拼接三列为复合标签(简单易实现)

直接将city、zone、category三列拼接为一个新的字符串列作为x轴刻度,代码示例:

import pandas as pd
import matplotlib.pyplot as plt

# 构造复合标签列,分隔符可根据需求调整
df['combine_key'] = df['city'] + '/' + df['zone'] + '/' + df['category']

# 绘制分组柱状图
df.plot(
    kind='bar',
    x='combine_key',
    y=['searches_ok', 'searches_null'],
    figsize=(12, 6),
    xlabel='城市/区域/分类',
    ylabel='搜索量',
    rot=45 # 旋转x轴标签避免文字重叠
)
# 自动调整布局防止标签被截断
plt.tight_layout()
plt.show()

方式2:设置多层x轴刻度(展示更清晰)

如果不想把三列拼成单一字符串,可以设置多层x轴刻度分层展示三个字段,代码示例:

import pandas as pd
import matplotlib.pyplot as plt

# 将三列设为多重索引
df = df.set_index(['city', 'zone', 'category'])

# 绘图
ax = df[['searches_ok', 'searches_null']].plot(
    kind='bar',
    figsize=(12, 6),
    ylabel='搜索量'
)
# 自定义x轴刻度标签,换行展示三个字段
ax.set_xticklabels([f'{c}\n{z}\n{ca}' for c,z,ca in df.index], rotation=0)
plt.tight_layout()
plt.show()

两种方式最终都能实现每个city/zone/category组合对应两根柱子展示searches_ok和searches_null数值的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:06:03