萧十郎
使用以下代码,我能够重现您的错误。import pandas as pdimport matplotlib.pyplot as pltfor k in range(8,10): lablist=[j for j in range(k)] vallist=[j for j in range(k)] df = pd.DataFrame({'lab':lablist, 'val':vallist}) img_width=1540 n_ind=len(vallist) leftside = (-0.0075)*(img_width-(n_ind*190)-50)/2 -n_ind*0.15 rightside = (-1)*leftside + n_ind - 1 ax = df.plot.bar(x='lab', y='val', rot=0,figsize=(10,5)) ax.set_xlim([leftside, rightside])错误存在于leftside和rightside计算中,当条数更改时,您尝试添加的空白空间不一致。通过取 x 轴的最小值和最大值并添加一个恒定间隙,您可以对齐图的所有条形for k in range(8,10): lablist=[j for j in range(k)] vallist=[j for j in range(k)] df = pd.DataFrame({'lab':lablist, 'val':vallist}) leftside = df['lab'].min()-0.75 rightside = df['lab'].max()+0.75 ax = df.plot.bar(x='lab', y='val', rot=0,figsize=(10,5)) ax.set_xlim([leftside, rightside])