无法使用 Pandas plot() 函数组合条形图和折线图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39560099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:01:50  来源:igfitidea点击:

Cannot combine bar and line plot using pandas plot() function

pythonpandasmatplotlibplot

提问by user1934212

I am plotting one column of a pandas dataframe as line plot, using plot() :

我正在使用 plot() 将Pandas数据框的一列绘制为线图:

df.iloc[:,1].plot()

and get the desired result:

并得到想要的结果:

enter image description here

在此处输入图片说明

Now I want to plot another column of the same dataframe as bar chart using

现在我想使用与条形图相同的数据框绘制另一列

ax=df.iloc[:,3].plot(kind='bar',width=1)

with the result:

结果:

enter image description here

在此处输入图片说明

And finally I want to combine both by

最后我想将两者结合起来

spy_price_data.iloc[:,1].plot(ax=ax)

which doesn't produce any plot.

这不会产生任何情节。

Why are the x-ticks of the bar plot so different to the x-ticks of the line plot? How can I combine both plots in one plot?

为什么条形图的 x-ticks 与线图的 x-ticks 如此不同?如何将两个地块合并为一个地块?

采纳答案by Bob Haffner

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

some data

一些数据

df = pd.DataFrame(np.random.randn(5,2))
print (df)
          0         1
0  0.008177 -0.121644
1  0.643535 -0.070786
2 -0.104024  0.872997
3 -0.033835  0.067264
4 -0.576762  0.571293

then we create an axes object (ax). Notice that we pass ax to both plots

然后我们创建一个轴对象(ax)。请注意,我们将 ax 传递给两个图

_, ax = plt.subplots()

df[0].plot(ax=ax)
df[1].plot(kind='bar', ax=ax)

enter image description here

在此处输入图片说明