我可以从不同的数据帧绘制两个Y轴的图形吗?

2024-04-18 21:44:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用谷歌趋势兴趣绘制一张股价图,但我无法将它们绘制在错误显示的同一张图中:

ValueError: x and y must have same first dimension, but have shapes (2094,) and (261,)

这就是我所拥有的:

import pandas_datareader.data as web
import pandas as pd
import matplotlib.pyplot as plt
from pytrends.request import TrendReq
pytrend = TrendReq()
plt.style.use('ggplot')

df = web.DataReader('ITUB4.SA', data_source='yahoo', start='2012-01-31', end='2020-07-21')
data = df.filter(['Close'])
print(df)

trend_list = ['ITUB4']
pytrend.build_payload(kw_list=['ITUB4'], geo='BR')
df_divo = pytrend.interest_over_time()
df_divo = df_divo.filter(['ITUB4'])
print(df_divo)

x = df.index
y1 = data['Close']
y2 = df_divo['ITUB4']
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
curve1 = ax1.plot(x, y1)
curve2 = ax2.plot(x, y2)
plt.plot()
plt.show()

提前谢谢


Tags: andimportwebpandasdfdataplothave
1条回答
网友
1楼 · 发布于 2024-04-18 21:44:50
  • xy1都来自df,有2094行。但是,y2来自pytrend,只有261行,这就是为什么要得到ValueError
  • 绘图的x轴采用日期时间格式。不需要用df.index绘制df_divo.ITUB4
import pandas as pd
import matplotlib.pyplot as plt
import pandas_datareader.data as web
from pytrends.request import TrendReq
pytrend = TrendReq()

# get yahoo data
df = web.DataReader('ITUB4.SA', data_source='yahoo', start='2012-01-31', end='2020-07-21')

# get ITUB4 data from pytrends
trend_list = ['ITUB4']
pytrend.build_payload(kw_list=trend_list, geo='BR')
df_divo = pytrend.interest_over_time()

# plot
fig, ax = plt.subplots()
ax.plot(df.index, 'Close', data=df, label='Close')
ax.plot(df_divo.index, 'ITUB4', data=df_divo, label='Interest over Time')
plt.legend()
plt.show()

enter image description here

相关问题 更多 >