【问题标题】:How to plot two time series data with different time frequency on same axis in python?如何在python的同一轴上绘制两个具有不同时间频率的时间序列数据?
【发布时间】:2020-07-18 00:52:56
【问题描述】:

我有 2 个时间序列数据。

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

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

【问题讨论】:

  • 条形图不能很好地与时间序列配合使用,尤其是与另一个时间序列一起绘制时。

标签: python pandas matplotlib plot


【解决方案1】:

我希望这是你想要的

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()

结果

【讨论】:

  • 谢谢等离子,这正是我正在寻找的。只是一个简单的问题:为什么我们在那里使用子图?我认为这仅在您需要在图表中绘制几个不同的数字时使用。有没有更直接的方法来实现这一点?
  • 我使用的是子图,因为没有任何参数,它默认为 1 行和 1 列。所以它创建了一个我习惯的轴。我希望这会有所帮助。
  • 知道了。我还在学习它。 gcf() 和 gca() 在获取对象(图形和轴)方面与 subplots() 做同样的工作吗?
  • 如果这个答案回答了你的问题。请标记为“已接受”。 meta.stackexchange.com/questions/5234/…
  • 完成。能否请您回答上述问题。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 2018-10-16
  • 2019-06-14
  • 2016-07-31
相关资源
最近更新 更多