繁体   English   中英

如何在 python 的同一轴上 plot 两个时间频率不同的时间序列数据?

[英]How to plot two time series data with different time frequency on same axis in python?

我有 2 个时间序列数据。

  1. ABC公司的每日股票回报
  2. 农行年收入

我想 plot 将这两个系列放在同一个图(相同的 x 轴)上,以便我可以直观地了解这两个数据如何相互关联,如下图所示。 如何使用 pandas 和 matplotlib 在 python 中实现这一点?

在此处输入图像描述

我希望这是你想要的

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

# Made up Stock price data
stock_price = np.random.random_sample(size=100)*20+np.exp(0.05*np.arange(100))
stock_price_df = pd.DataFrame({'dates':pd.date_range(start='1/1/2018', end='1/08/2023',periods=len(stock_price)), 'stock price':stock_price})
stock_price_df = stock_price_df.set_index('dates')

# Made up revenue data
revenue = np.random.random_sample(size=100)*20+np.exp(0.02*np.arange(100))
revenue_df= pd.DataFrame({'dates':pd.date_range(start='1/1/2018', end='1/08/2023',periods=len(revenue)), 'revenue': revenue})
revenue_df = revenue_df.set_index('dates')
revenue_df_agg = revenue_df.resample('Y').mean().reset_index()

# Plot two of them together
fig, ax = plt.subplots()
ax.bar(pd.to_datetime(revenue_df_agg['dates'].dt.year, format='%Y'), revenue_df_agg['revenue'], width=200)
ax.set_ylabel('Revenue')
ax1 = ax.twinx()
s = stock_price_df['stock price'].plot(ax = ax1, style = '-r')
ax1.set_ylabel('Stock price')
ax1.yaxis.label.set_color('r')
ax1.yaxis.label.set_color('r')
ax1.tick_params(axis='y', colors='r')
plt.savefig('collage-2.png')
plt.show()

结果是

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM