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

Matplotlib柱状图Y轴未从0起始,设置ylim无效求助

Matplotlib柱状图Y轴范围设置无效的解决办法

问题场景

用Matplotlib绘制柱状图时,Y轴默认以数据最小值(8.88)作为起始点,想要将Y轴范围固定为0到15,但调用plt.ylim(0, 15)没有效果。

相关代码:

data = {'Average Time of 1st Instance':average_value1, 'Average Time of 2nd Instance':average_value2, 'Average Time of 3rd Instance':average_value3}  
instances = list(data.keys())  
times = list(data.values())  
fig = plt.figure(figsize = (10, 5))
plt.bar(instances, times, color ='blue', width = 0.4)
plt.xlabel('Instance of ++HSS')
plt.ylabel('Time in Seconds')
plt.title('Time Taken to run the Three Instances of ++HSS')  
plt.show()

使用的数据:
average_value1 = 8.88
average_value2 = 11.86
average_value3 = 11.36

当前生成的柱状图Y轴起始于8左右,无法达到预期的0-15范围。


解决方法

问题核心是**plt.ylim()的调用顺序错误**——必须将它放在plt.bar()绘图之后、plt.show()显示之前。因为plt.bar()执行时会自动调整轴范围来适配数据,只有在绘图完成后设置轴范围,才能覆盖自动调整的结果。

修改后的完整代码:

average_value1 = 8.88
average_value2 = 11.86
average_value3 = 11.36

data = {'Average Time of 1st Instance':average_value1, 'Average Time of 2nd Instance':average_value2, 'Average Time of 3rd Instance':average_value3}  
instances = list(data.keys())  
times = list(data.values())  

fig = plt.figure(figsize = (10, 5))
plt.bar(instances, times, color ='blue', width = 0.4)
plt.xlabel('Instance of ++HSS')
plt.ylabel('Time in Seconds')
plt.title('Time Taken to run the Three Instances of ++HSS')
# 调整Y轴范围:放在绘图后、显示前
plt.ylim(0, 15)
plt.show()

这样设置后,Y轴会从0开始,上限固定为15,能完整展示所有柱状条的高度对比,避免自动轴范围带来的视觉偏差。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:23:14