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

如何修改Pandas柱状图代码,显示Ref列值而非默认索引?

解决Pandas柱状图x轴显示Ref列值的问题

你的柱状图x轴只显示默认整数索引,没展示Ref列的F、C等值,核心原因是data['PC100'].plot()默认使用DataFrame的内置整数索引作为x轴标签。下面提供两种简单的修改方式:

方法一:将Ref列设为DataFrame索引

直接把Ref列设置为数据的索引,绘图时会自动用索引值作为x轴标签:

import pandas as pd
import matplotlib.pyplot as plt

data = pd.DataFrame({'Ref': ['F', 'C', 'H', 'B', 'G', 'A', 'D', 'E'],
                     'Nombre Pieces': [150, 130, 100, 60, 30, 30, 20, 10],
                     'PC100': [28.301887, 52.830189, 71.698113, 83.018868, 88.679245, 94.339623, 98.113208, 100.000000],
                     'categories': ['a', 'a', 'a', 'b', 'b', 'b', 'b', 'b']})

colors = {'a': 'red', 'b': 'blue'}

# 将Ref列设为数据索引
data.set_index('Ref', inplace=True)
# 绘制柱状图
data['PC100'].plot(kind='bar', color=data['categories'].map(colors))

plt.show()

方法二:手动设置x轴标签

如果不想修改原数据的索引结构,可以用plt.xticks()手动指定x轴的位置和对应标签:

import pandas as pd
import matplotlib.pyplot as plt

data = pd.DataFrame({'Ref': ['F', 'C', 'H', 'B', 'G', 'A', 'D', 'E'],
                     'Nombre Pieces': [150, 130, 100, 60, 30, 30, 20, 10],
                     'PC100': [28.301887, 52.830189, 71.698113, 83.018868, 88.679245, 94.339623, 98.113208, 100.000000],
                     'categories': ['a', 'a', 'a', 'b', 'b', 'b', 'b', 'b']})

colors = {'a': 'red', 'b': 'blue'}

# 绘制柱状图
data['PC100'].plot(kind='bar', color=data['categories'].map(colors))
# 手动绑定x轴位置与Ref列值
plt.xticks(range(len(data)), data['Ref'])

plt.show()

两种方法都能让x轴显示Ref列的对应值,可根据需求选择。

内容的提问来源于stack exchange,提问作者Jean-Pat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 07:42:40