如何调整Matplotlib的y轴刻度以显示极小数值的误差棒?
如何调整Matplotlib Y轴刻度以显示误差棒?
我正在尝试调整y轴刻度,让误差棒能够正常显示,恳请帮忙!
当前代码
import numpy as np import matplotlib import matplotlib.pyplot as plt # 如果使用Jupyter notebook,添加: %matplotlib inline x = ntermsList y = allPmuCycleCountAverages xerr = 0 yerr = allPmuCycleCountStandardDeviations fig, ax = plt.subplots() ax.errorbar(x, y, xerr=xerr, yerr=yerr,fmt='-o') ax.set_xlabel('x-axis') ax.set_ylabel('y-axis') ax.set_title('Line plot with error bars') ax.set_xticks(ntermsList) ax.set_xticklabels(ntermsList) ax.set_yticks(allPmuCycleCountAverages) ax.yaxis.grid(True) plt.show()
当前生成的图表

尝试过的无效方案
plt.ylim(-1, 1) plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True plt.yticks(np.arange(min(y), max(y)+0.5, 0.01))
我的需求是:让y轴刻度足够贴近数据点,从而显示出误差棒。
问题根源
你当前代码里的ax.set_yticks(allPmuCycleCountAverages)强制将y轴刻度设置为数据点的y值,覆盖了Matplotlib自动计算的轴范围,导致误差棒被不合理的刻度/范围压缩或隐藏;而plt.ylim(-1,1)如果和你的实际数据值差距过大,也会把误差棒压缩到几乎看不见。
解决方案
1. 移除强制y轴刻度,让Matplotlib自动适配
删掉ax.set_yticks(allPmuCycleCountAverages)这一行,Matplotlib会根据数据和误差棒的范围自动计算合适的y轴范围与刻度,误差棒就能正常显示。
2. 手动微调y轴范围(可选)
如果自动适配的效果不够理想,可以基于数据和误差范围手动设置y轴上下限,再添加少量余量保证美观:
# 计算包含误差的y轴极值 y_min = min(y) - max(yerr) y_max = max(y) + max(yerr) # 添加5%的余量 ax.set_ylim(y_min * 0.95, y_max * 1.05)
3. 自定义均匀刻度(可选)
如果需要自定义刻度但不想破坏误差棒显示,用np.linspace生成均匀分布的刻度,而非直接使用数据点y值:
ax.set_yticks(np.linspace(y_min, y_max, 5)) # 生成5个均匀分布的刻度
完整修改后的代码
import numpy as np import matplotlib import matplotlib.pyplot as plt # 如果使用Jupyter notebook,添加: %matplotlib inline x = ntermsList y = allPmuCycleCountAverages xerr = 0 yerr = allPmuCycleCountStandardDeviations fig, ax = plt.subplots() ax.errorbar(x, y, xerr=xerr, yerr=yerr,fmt='-o') ax.set_xlabel('x-axis') ax.set_ylabel('y-axis') ax.set_title('Line plot with error bars') ax.set_xticks(ntermsList) ax.set_xticklabels(ntermsList) # 手动设置y轴范围(可选) y_min = min(y) - max(yerr) y_max = max(y) + max(yerr) ax.set_ylim(y_min * 0.95, y_max * 1.05) # 可选:自定义均匀刻度 # ax.set_yticks(np.linspace(y_min, y_max, 5)) ax.yaxis.grid(True) plt.show()
内容的提问来源于stack exchange,提问作者SiennaRose
相关产品推荐
相关产品推荐

