Matplotlib errorbar图表上下存在多余空白,如何消除?
解决Errorbar图表上下多余空白的问题
嘿,我来帮你搞定这个图表上下空白的问题!你的代码里设置了fig.set_figheight(len(x))来适配50个分类标签,但Matplotlib默认会给y轴(也就是你这个横向图的纵向轴)预留一些边距,这就导致了顶部和底部出现多余的空白区域。
具体解决方案
你只需要在代码里添加一行,手动设置y轴的范围,让它刚好贴合所有的分类标签:
import pandas as pd import numpy as np import random import matplotlib.pyplot as plt from matplotlib.transforms import Affine2D random.seed(1) df = pd.DataFrame(np.random.randn(50, 1), columns=["parameter"]) df["standard_error"]= ((df.parameter**2)**0.5)/2 name = "plot" x = ["A"+str(x) for x in df.index.tolist()] y1 = df.parameter yerr1 = df.standard_error fig, ax = plt.subplots() fig.set_figheight(len(x)) plt.rc('axes', labelsize=22) plt.grid(b=True, which='major', color='#666666', linestyle='-', alpha=0.2) trans1 = Affine2D().translate(-0.1, 0.0) + ax.transData trans2 = Affine2D().translate(+0.1, 0.0) + ax.transData er1 = ax.errorbar(y1, x, xerr=yerr1, marker="o", linestyle="none", transform=trans1) ax.axvline(x=0, color="black") # 添加这行代码,设置y轴范围,消除空白 ax.set_ylim(-0.5, len(x)-0.5) plt.savefig(name + '.png', bbox_inches='tight')
为什么这样有效?
你的分类标签x对应y轴的位置是从0到49(因为df的索引是0-49)。设置ylim(-0.5, 49.5)后,y轴的范围刚好覆盖每个标签的上下边界,完全消除了Matplotlib默认添加的边距。
另外,你也可以用ax.margins(y=0)来替代set_ylim,它会自动移除轴的边距,效果类似,但set_ylim能更精确地控制范围,适合这种固定数量的分类场景。
内容的提问来源于stack exchange,提问作者Hans Geber
相关产品推荐
相关产品推荐

