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

如何制作基于DataFrame索引而非标签的matplotlib柱状图?

实现以DataFrame索引为X轴的竖柱状图(从0延伸至对应数值)

你要的是每个X轴刻度(对应DataFrame的索引)都有一根从Y轴基线(比如0)延伸到对应数据值的竖条,用Matplotlib可以直接实现,步骤如下:

1. 基础实现代码

先构造示例DataFrame,然后用plt.bar()指定X轴为DataFrame的索引即可:

import pandas as pd
import matplotlib.pyplot as plt

# 构造带自定义索引的DataFrame(替换成你的真实数据)
df = pd.DataFrame(
    {'数值列': [12, 25, 18, 30, 22]},
    index=['组别A', '组别B', '组别C', '组别D', '组别E']
)

# 绘制柱状图
plt.figure(figsize=(8, 5))
# x参数传入df.index,直接用索引作为X轴刻度;height传入对应的数据列
plt.bar(x=df.index, height=df['数值列'], width=0.6, color='#7ccd7c')

# 设置图表标签
plt.xlabel('索引标签')
plt.ylabel('数值')
plt.title('以DataFrame索引为X轴的柱状图')

# 自动调整布局,防止标签被截断
plt.tight_layout()
plt.show()

2. 处理特殊索引(如日期型)

如果你的DataFrame索引是日期格式,只需额外调整X轴标签的旋转角度,避免重叠:

# 日期索引示例
df_date = pd.DataFrame(
    {'数值列': [15, 20, 17]},
    index=pd.date_range('2024-01-01', periods=3)
)

plt.figure(figsize=(8, 5))
plt.bar(x=df_date.index, height=df_date['数值列'], color='#7ccd7c')
# 旋转日期标签
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

常见报错原因

之前报错大概率是X轴参数传错:比如误传了数据的位置序号而非索引,或者索引类型与绘图函数不兼容(比如未处理的复杂索引),按上面的方式直接传入df.index即可解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 12:54:58