我可能做错了什么,但我正在努力实现以下目标:
# 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')
关于Python Pandas DataFrame - 无法在同一轴上绘制条形图和线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31813820/