【问题标题】:Can I plot a graph with two Y axis from different Data Frames?我可以用来自不同数据框的两个 Y 轴绘制图表吗?
【发布时间】:2020-11-12 09:37:19
【问题描述】:

我正在尝试绘制股票价格及其对 Google 趋势的兴趣的图表,但我无法将它们绘制在与错误所示相同的图表中:

ValueError: x 和 y 必须具有相同的第一维,但形状为 (2094,) 和 (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()

提前致谢!

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:
    • xy1 都来自 df 并且有 2094 行。但是,y2 来自 pytrend,并且只有 261 行,这就是您获得 ValueError 的原因。
    • 绘图的 x 轴采用日期时间格式。无需绘制df_divo.ITUB4df.index
    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()
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    • 2016-10-27
    • 2020-05-02
    • 2015-04-04
    • 2021-03-29
    • 2019-03-10
    相关资源
    最近更新 更多