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

如何调整Matplotlib柱状图Y轴灵敏度?解决数值差异难展示问题

Matplotlib柱状图Y轴调整无效的解决方案

用户问题

我有三组Y轴数值,希望分别对应X轴刻度1、2、3绘制柱状图以展示数值差异,数值如下:

0.9999893294851471
0.9999997569910387
1.0

尝试使用ylim函数调整Y轴范围但无效果,代码如下:

import matplotlib.pyplot as plt
x=[1,2,3]
y=[0.9999893294851471,0.9999997569910387,1.0]
plt.bar(x,y,align='center') 
plt.plot(x,y, 'r--', label='Default')  
plt.xlabel("tick") 
plt.ylabel("values") 
plt.ylim(0.9999800, 0.9999999) 
plt.show()

问题原因

你的ylim上限设置为0.9999999,但第三组数值是1.0,超过了这个上限。Matplotlib会自动调整Y轴范围以容纳所有数据,导致自定义的ylim被覆盖,无法达到预期效果。

解决办法

1. 修正Y轴范围,包含所有数据

调整ylim的上下限,确保覆盖所有Y值,同时缩小范围放大数值差异:

import matplotlib.pyplot as plt
x=[1,2,3]
y=[0.9999893294851471,0.9999997569910387,1.0]
plt.bar(x,y,align='center') 
plt.plot(x,y, 'r--', label='Default')  
plt.xlabel("tick") 
plt.ylabel("values") 
# 调整范围,包含所有数据且聚焦差异区间
plt.ylim(0.999988, 1.000001)
plt.show()

2. 优化刻度显示,突出数值差异

由于数值接近1,可关闭科学计数法并保留精确刻度,配合ylim聚焦差异:

import matplotlib.pyplot as plt
x=[1,2,3]
y=[0.9999893294851471,0.9999997569910387,1.0]
plt.bar(x,y,align='center') 
plt.plot(x,y, 'r--', label='Default')  
plt.xlabel("tick") 
plt.ylabel("values") 
# 关闭科学计数法,显示完整刻度
plt.ticklabel_format(useOffset=False, style='plain')
# 聚焦差异区间
plt.ylim(0.999988, 1.0)
plt.show()

3. 绘制与基准值的差值图表

如果仅需展示与1的差异,直接计算差值绘图,差异会更直观:

import matplotlib.pyplot as plt
x=[1,2,3]
y=[0.9999893294851471,0.9999997569910387,1.0]
# 计算每个数值与1的差值
diff_values = [1 - val for val in y]
plt.bar(x, diff_values, align='center') 
plt.plot(x, diff_values, 'r--', label='Difference from 1')  
plt.xlabel("tick") 
plt.ylabel("Difference from 1") 
plt.legend()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 09:15:23