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

如何使用Python绘制与Excel效果一致的分类数据图表

实现方案

提前安装依赖库:
pip install pandas matplotlib

完整可运行代码

import pandas as pd
import matplotlib.pyplot as plt
from io import StringIO

# 1. 读取数据集,无需额外存文件,直接运行即可
csv_data = """Country,state,sex,dist,population,LL,UL
IND,AP,F,EG,82,80,150
IND,AP,F,WG,150,80,150
IND,AP,F,VZA,95,80,150
IND,AP,F,BZA,116,80,150
IND,AP,M,EG,180,80,150
IND,AP,M,WG,158,80,150
IND,AP,M,VZA,77,80,150
IND,AP,M,BZA,114,80,150
IND,UP,F,A,86,80,150
IND,UP,F,B,179,80,150
IND,UP,M,C,83,80,150
IND,UP,M,D,146,80,150
"""
data = pd.read_csv(StringIO(csv_data))

# 2. 构造X轴分类标签,支持多维度组合匹配Excel分类逻辑
# 可根据你的实际需求调整拼接的字段,比如只保留dist+sex也可以
data['x_label'] = data['state'] + '-' + data['dist'] + '-' + data['sex']
x = range(len(data))
population = data['population']
ll = data['LL']
ul = data['UL']

# 3. 绘图
plt.figure(figsize=(16, 7))
# 绘制人口柱形
plt.bar(x, population, width=0.6, label='population', color='#1f77b4')
# 绘制上下限参考线
plt.hlines(y=ll, xmin=[i-0.3 for i in x], xmax=[i+0.3 for i in x], color='#d62728', linewidth=2, label='LL')
plt.hlines(y=ul, xmin=[i-0.3 for i in x], xmax=[i+0.3 for i in x], color='#2ca02c', linewidth=2, label='UL')

# 4. 配置X轴,解决多列名对应问题
plt.xticks(x, data['x_label'], rotation=45, ha='right')
# 若需要多级分层X轴(和Excel多分类轴完全一致),可启用下方代码
# ax = plt.gca()
# state_pos = data.groupby('state').apply(lambda df: df.index.mean()).values
# state_labels = data['state'].unique()
# for pos, label in zip(state_pos, state_labels):
#     ax.text(pos, -25, label, ha='center', fontweight='bold', fontsize=12)

# 通用样式配置
plt.xlabel('State - District - Sex')
plt.ylabel('Value')
plt.title('Population Classification Chart')
plt.legend()
plt.tight_layout()
plt.show()

核心问题解决说明

你之前遇到的无法将列名配置到X轴的问题,本质是需要把多维度分类字段先拼接为组合标签,或者通过分层渲染的方式分别展示不同层级的列值,上述代码两种方式都支持,可根据你的Excel图实际样式调整。
如果需要区分性别颜色、增加分组间隔等其他样式,直接修改柱形颜色、插入空白索引即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:30:01