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
我想知道你的问题是否与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)
感谢@DizietAsahi - 发现这是DatetimeIndex作为x值的问题.整数值与上面的@DizietAsahi代码一起使用.
在熊猫提交以下内容:
https://github.com/pydata/pandas/issues/10761#issuecomment-128671523