在一个图中叠加两个数据框

时间:2018-04-23 21:29:11

标签: python python-3.x pandas numpy matplotlib

我有两个不同的数据帧,它们的大小相同,并且Date列的值相同。

        Date     Open     High      Low    Close        Volume    Market Cap
0 2018-04-16  8337.57  8371.15  7925.73  8058.67  5.631310e+09  1.415710e+11
1 2018-04-15  7999.33  8338.42  7999.33  8329.11  5.244480e+09  1.358120e+11
2 2018-04-14  7874.67  8140.71  7846.00  7986.24  5.191430e+09  1.336820e+11
3 2018-04-13  7901.09  8183.96  7758.93  7895.96  7.764460e+09  1.341140e+11
4 2018-04-12  6955.38  7899.23  6806.51  7889.25  8.906250e+09  1.180480e+11

两个数据框都具有相同的结构。相同的列索引和相同的行数。

print(df.dtypes)
print(df2.dtypes)

两者都给予

Date          datetime64[ns]
Open                 float64
High                 float64
Low                  float64
Close                float64  
Volume               float64
Market Cap           float64
dtype: object

我想在x轴上绘制Date,在y轴上绘制Market Cap。根据我的研究,我认为不可能合并数据框的绘图功能,即。

df.plot(x='Date', y = 'Market Cap', kind = 'line')
df2.plot(x='Date', y = 'Market Cap', kind = 'line')

我的问题是获取我想要创建的图表的好方法是什么?我应该使用groupby,key还是pyplot

要清楚我想要单独的两个图表的叠加:

seperate two graphs

到目前为止,我已尝试过代码:

import matplotlib.pyplot as plt

# Init subplots
fig, axes = plt.subplots(1,1);

# Init ax with the first plot.
ax = df['Market Cap'].plot()

# Plot second df using ax from the first plot.
_ = df2['Market Cap'].plot(ax = ax)

plt.show()

导致叠加不当:

results in improper overlay

2 个答案:

答案 0 :(得分:1)

ax = df.plot(x='Date', y = 'Market Cap', kind = 'line')
df2.plot(x='Date', y = 'Market Cap', kind = 'line', ax=ax)

results由@scottBoston提供

答案 1 :(得分:-1)

尝试使用子图。

import matplotlib.pyplot as plt

# Init subplots
fig, axes = plt.subplots(1,1);

# Init ax with the first plot.
ax = df['Market Cap'].plot()

# Plot second df using ax from the first plot.
_ = df2['Market Cap'].plot(ax = ax)

plt.show()