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

使用matplotlib.pyplot绘制柱状图出现空图问题求助

解决Matplotlib柱状图仅显示坐标轴无柱形的问题

问题原因

你的x轴数值跨度极大(从1288.7到25596.797),而plt.bar()默认柱宽为0.8,这个宽度相对于x轴刻度间的间距(最小都有2698.4)来说过于微小,导致柱子在图上几乎不可见,最终呈现出只有坐标轴的空图。

解决方案

有两种常用的解决方式:

方案1:手动设置合适的柱宽

根据x轴数值的间距,设置足够大的width参数,让柱子能在图上显示出来:

import matplotlib.pyplot as plt

x_vals = [1288.7, 9386.9, 12086.3, 14785.7, 17485.1, 20184.5, 22883.9, 25596.797]
height_vals = [0.22772277227722773, 0.5, 0.5, 0.4430379746835443, 0.3658696364231903, 0.39693539122862276, 0.4186823730508119, 0.44525257342712926]

plt.bar(x=x_vals, height=height_vals, width=500)
plt.show()

对应pandas数据的场景:

fig, ax = plt.subplots(1,1)
ax.bar(
    x=list(df.index),
    height=list(df["column1"]),
    width=500  # 根据实际数据调整宽度
)
plt.show()

方案2:将x轴转为类别索引(适合非连续数值场景)

如果你的x轴数值是类别而非连续数据,可以用索引位置作为x轴,再将原数值设置为x轴标签,这样柱子宽度会恢复正常:

import matplotlib.pyplot as plt

x_vals = [1288.7, 9386.9, 12086.3, 14785.7, 17485.1, 20184.5, 22883.9, 25596.797]
height_vals = [0.22772277227722773, 0.5, 0.5, 0.4430379746835443, 0.3658696364231903, 0.39693539122862276, 0.4186823730508119, 0.44525257342712926]

plt.bar(x=range(len(x_vals)), height=height_vals)
plt.xticks(range(len(x_vals)), x_vals, rotation=45)  # 旋转标签避免重叠
plt.show()

对应pandas数据的场景:

fig, ax = plt.subplots(1,1)
ax.bar(
    x=range(len(df)),
    height=list(df["column1"])
)
ax.set_xticks(range(len(df)))
ax.set_xticklabels(df.index, rotation=45)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 06:22:45