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

Wil*_*llZ 4 python matplotlib pandas

我可能会做错事但我正在努力实现以下目标:

# 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')
Run Code Online (Sandbox Code Playgroud)

我希望看到的图表有些酒吧和线路.然而,我最终得到的只是线条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')
Run Code Online (Sandbox Code Playgroud)

然而,这并不完美,因为我不得不使用label标签,否则传说将不包括df[col2]...

那里的任何人都有一个更优雅的解决方案,使条形和线条出现?

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

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

Diz*_*ahi 5

我想知道你的问题是否与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')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这仅显示线而不是条形图

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')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 找出为什么我无法得到你的结果.当我有数据框的DatetimeIndex时会出现问题.对于你的代码,如果你尝试:`drange = pd.date_range(start ='2015-07-01',end ='2015-07-10',freq ='D'); df = pd.DataFrame(data = np.random.random_sample((10,3)),index = drange,columns = ['col1','col2','col3']);`如果你重现我的问题用上面的代码绘制它,即使用`plt.hold(True)`.. (2认同)

Wil*_*llZ 5

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

在熊猫提交以下内容:

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