python - 如何在python中的同一轴上绘制两个具有不同时间频率的时间序列数据?
问题描述
我有 2 个时间序列数据。
- ABC公司的每日股票回报
- 农行年收入
我想将这两个系列绘制在同一个图(相同的 x 轴)上,以便我可以直观地了解这两个数据如何相互关联,如下图所示。如何在 python 中使用 pandas 和 matplotlib 实现这一点?
解决方案
我希望这是你想要的
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()
结果是
推荐阅读
- python-3.x - Case对象和When Object的Django查询集,---
- batch-file - 如何在使用磁盘部分和批处理文件时将所有内容从驱动器 A 复制到驱动器 B?
- javascript - 带有导入图像的模板文字
- linux - 如何在 Linux 终端中按排序顺序输出 3 个最频繁的模式匹配?
- r - 将反应对象调用到渲染输出函数中
- python - chatterbot 数学评估时间和减去不工作
- python - Pandas DataFrame 查询 Python
- java - 有没有办法同时实现读取进程的 OutputStream 并将其输出重定向到标准 io?
- python - “with mouse.Listener”如何在 pynput 中工作?
- reactjs - 导入 .csv 文件时反应 D3 错误 404