将两个数据帧绘制成一个图



我有2个数据帧,我已经将日期列设置为datetime格式,但它仍然返回Value错误。我可以知道是因为带有2个数据帧的x轴不同吗?

import pandas as pd
import matplotlib.pyplot as plt
df_1 = pd.read_csv("df.csv")
df_1.head()
symbol  net_revenue
date        
2015-03-31  ETSY    58543
2015-06-30  ETSY    61365
2015-09-30  ETSY    65696
2015-12-31  ETSY    87895
2016-03-31  ETSY    81847
import pandas_datareader.data as web
stock = 'ETSY'
start ='2013-12-31'
import datetime as dt
end = '2020-09-30'
df2 = web.DataReader(stock,'yahoo',start,end)
df2.head()
High    Low Open    Close   Volume  Adj Close
Date                        
2015-04-16  35.740002   28.219999   31.000000   30.000000   19763300    30.000000
2015-04-17  30.299999   26.510000   29.770000   27.580000   3965500 27.580000
2015-04-20  28.900000   24.870001   28.770000   24.900000   3076200 24.900000
2015-04-21  26.040001   24.559999   24.969999   25.750000   2184700 25.750000
2015-04-22  26.240000   24.950001   26.000000   25.120001   1442500 25.120001
... ... ... ... ... ... ...
2020-09-24  116.099998  109.519997  112.550003  113.680000  4339000 113.680000
2020-09-25  118.684998  113.010002  113.699997  118.279999  2572600 118.279999
2020-09-28  123.949997  119.190002  120.370003  123.690002  3456500 123.690002
2020-09-29  125.699997  121.260002  123.610001  123.230003  2618000 123.230003
2020-09-30  125.589996  120.139999  123.190002  121.629997  2524500 121.629997

#将2个数据帧绘制成1个图

x = df1.index
y1 = df1['net_revenue']
y2 = df2['Adj Close']
fig, ax1 = plt.subplots(figsize=(20,8))
ax2 = ax1.twinx()
curve1 = ax1.plot(x, y1, label='etsy', color='r')
curve2 = ax2.plot(x, y2, label='close', color='b')
plt.plot()

错误:

ValueError: x and y must have same first dimension, but have shapes (23,) and (1376,)

您的df1df2具有不同的长度。尝试根据每个数据帧自己的索引绘制每个数据帧。

# I would suggest passing what you plot directly to the function
# that way you know which you are plotting against which
ax1.plot(df1.index, df1['net_revenue'], label='etsy', color='r')
ax2.plot(df2.index, df2['Adj Close'], label='close', color='b

你也可以使用熊猫绘图:

df1['net_revenue'].plot(ax=ax1, label='etsy', color='r')
df2['Adj Close'].plot(, ax=ax2, label='close', color='b')

打印前请记住将索引转换为datetime类型。

最新更新