python - Pandas 条形图切断了x轴的两端

标签 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轴。

谢谢

最佳答案

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

# 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

关于python - Pandas 条形图切断了x轴的两端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58957532/

相关文章:

python - 使用字典将重复行映射到原始行 - Python 3.6

python - 创建新的 python 对象似乎是同一个对象

Python elif 无法按预期进行字符串查找

python - 如何获取 Pandas 数据框中组中 B 列的最后一条记录和 A 列的总和?

python-3.x - 在将多头 pandas 数据帧输出到 excel 时摆脱索引

python - 将列列表更改为不同数据类型的更Pythonic(或pandorable)的方法

python - 如果另一列中的行满足条件则填充 nan

python - 将 pandas DataFrame 与 NaN 合并以查找缺失行

python - PyGame 安装 Mac OS X

python - 每个组的值的出现次数作为单独的列