无法在同一轴上绘制条形和线形

无法在同一轴上绘制条形和线形

本文介绍了Python Pandas DataFrame-无法在同一轴上绘制条形和线形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I might be doing something wrong but I'm struggling to achieve the below:

# 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]之前的内容似乎已被覆盖.

I expected to see a chart with both some bars and a line. However, what I end up with is only the line for df[col2], the bars from df[col1] are just not on the chart. Whatever is before df[col2] seem to have been overwritten.

我通过以下方法解决了这个问题:

I got around this with:

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] ...

However, this isn't perfect as I had to use label tags otherwise legends will not included items for df[col2]...

外面有没有更优雅的解决方案,可以同时显示条形和线条?

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

** Edit **Thanks to @DizietAsahi - Found out that this is a problem with DatetimeIndex as x-values. Filed the following at Pandas:

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

推荐答案

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

Thanks to @DizietAsahi - Found out that this is a problem with DatetimeIndex as x-values. Integer values work with @DizietAsahi's code above.

在Pandas提交了以下内容:

Filed the following at Pandas:

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

这篇关于Python Pandas DataFrame-无法在同一轴上绘制条形和线形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:15