熊猫条形图切断了x轴的两端

时间:2019-11-20 15:08:21

标签: python pandas dataframe matplotlib

我有一个DataFrame,并且想要一个相当简单的水平条形图。但是,x轴的边缘太紧,我的第一项和最后一项的值都被切除了:

df = pd.DataFrame(np.random.rand(10,3))
df.columns = ['col1','col2','col3']
df.index = ['ind1','ind2','ind3','ind4','ind5','ind6','ind7','ind8','ind9','ind10']
df['col4'] = 0.5
df.drop('col4',axis=1).plot.bar(figsize=(15,8));
df['col4'].plot(kind='line',color='black',linestyle='dashed',label='All-time average',legend=True);

Jupyter Notebook中的图表看起来像这样

需要进行哪些更改才能扩展x轴。关于此的大多数问题似乎都涵盖了可以设置x_lim的连续数据,但是我有一个明确的x轴。

谢谢

1 个答案:

答案 0 :(得分:0)

您还可以在传递正确的轴的同时更改打印顺序:

# create axis object
fig, ax = plt.subplots()
df = pd.DataFrame(np.random.rand(10,3))
df.columns = ['col1','col2','col3']
df.index = ['ind1','ind2','ind3','ind4','ind5','ind6','ind7','ind8','ind9','ind10']
df['col4'] = 0.5

# line plot first
df['col4'].plot(kind='line',
                color='black',linestyle='dashed',
                label='All-time average',legend=True,
                ax=ax
               );
# bar plot later so it aligns axis automatically
df.drop('col4',axis=1).plot.bar(ax=ax);

输出:

enter image description here