繁体   English   中英

Python Pandas DataFrame - 无法在同一轴上绘制条形和线条

[英]Python Pandas DataFrame - Cannot plot bars and lines on the same axes

我可能做错了什么,但我正在努力实现以下目标:

# plot bars and lines in the same figure, sharing both x and y axes.
df = some DataFrame with multiple columns
_, ax = plt.subplots()
df[col1].plot(kind='bar', ax=ax)
df[col2].plot(ax=ax, marker='o', ls='-')
ax.legend(loc='best')

我期望看到的图表一些酒吧和线路。 但是,我最终得到的只是df[col2]来自df[col1]的条形不在图表上 df[col2]之前的任何内容似乎都被覆盖了。

我解决了这个问题:

df[col1].plot(kind='bar', ax=ax, label=bar_labels)
ax.plot(df[col2], marker='o', ls='-', label=line_labels)
ax.legend(loc='best')

但是,这并不完美,因为我必须使用label标签,否则图例将不包含df[col2] ...

有没有人有更优雅的解决方案来同时显示条形和线条?

** 编辑 ** 感谢 @DizietAsahi - 发现这是 DatetimeIndex 作为 x 值的问题。 在 Pandas 上提交了以下内容:

https://github.com/pydata/pandas/issues/10761#issuecomment-128671523

我想知道你的问题是否与你的情节的hold状态有关......

这有效:

df = pd.DataFrame(np.random.random_sample((10,2)), columns=['col1', 'col2'])
fig, ax = plt.subplots()
plt.hold(True)
df['col1'].plot(kind='bar', ax=ax)
df['col2'].plot(ax=ax, marker='o', ls='-')
ax.legend(loc='best')

在此处输入图片说明

这仅显示线条而不是条形图

df = pd.DataFrame(np.random.random_sample((10,2)), columns=['col1', 'col2'])
fig, ax = plt.subplots()
plt.hold(False)
df['col1'].plot(kind='bar', ax=ax)
df['col2'].plot(ax=ax, marker='o', ls='-')
ax.legend(loc='best')

在此处输入图片说明

感谢@DizietAsahi - 发现这是 DatetimeIndex 作为 x 值的问题。 整数值与上面@DizietAsahi 的代码一起使用。

在 Pandas 上提交了以下内容:

https://github.com/pydata/pandas/issues/10761#issuecomment-128671523

我在使用 DatetimeIndex 作为 x 值时遇到了同样的问题。 我无法在github 上进行 hack,使用带有 Python 2.7.11 的 Jupyter Notebook 版本 4.2.0。 我按月将两列分组以绘制为条形图,然后将原始值叠加为折线图。

我的解决方案是使用 matplotlib 绘制条形图和线条,这是我让它工作的唯一方法。

import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
%matplotlib inline

df = pd.read_excel('data.xlsx', index_col='Date')
fig, ax = plt.subplots(figsize=(15,10)) 
ax.hold(True)
g = df.groupby(pd.TimeGrouper("M"))
width=10

ax.bar(g.sum().index, g['Money Out'].sum(),width=width, color='r',label='Money Out')
ax.bar(g.sum().index, g['Money in'].sum(),width=-width,color='g', label='Money In')
ax.plot(df[['Balance']], color='black', lw=1, ls='-',label='Balance')  

ax.legend(loc='best')

图片

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM