如何使用matplotlib绘制具有两个不同时间刻度的周期图?

2024-04-27 03:46:20 发布

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

我有两个不同的股票图表。我喜欢比较两个不同时期的相对发展,这两个时期的长度不一样。附加的代码正确地完成了这一任务,尽管代码效率很低。 我无法解决的是,在各自的子地块上方或下方正确绘制两个子地块的时间轴。在第二个子地块下,时间轴始终完全拉伸,我使用了“sharex=ax3”? Jupyter笔记本的代码,Python 3.6。详情如下:

import matplotlib.pyplot as plt
from matplotlib import style
import matplotlib.dates as mdates
from mpl_finance import candlestick2_ohlc
import pandas as pd
import pandas_datareader.data as web
import matplotlib.dates as mdates
import matplotlib.cbook as cbook
from matplotlib.dates import date2num, DayLocator, DateFormatter
import sys
import warnings

df1=pd.read_csv('/var/samba/FD/YHO/Index/^HUI.csv', parse_dates=True, index_col=0)
df2=pd.read_csv('/var/samba/FD/YHO/Index/^GSPC.csv', parse_dates=True, index_col=0)

years = mdates.YearLocator()   # every year
months = mdates.MonthLocator()  # every month
years_fmt = mdates.DateFormatter('%Y')

start1=datetime(2007,10, 1) 
end1=datetime(2009,10, 1)
df1_1=df1[start1:end1]
df2_1=df2[start1:end1]

df1_1['pct'] = df1_1['Close'].pct_change().cumsum()
df2_1['pct'] = df2_1['Close'].pct_change().cumsum()
df1_1['Elapsed_days'] = df1_1.index-df1_1.index[0]
df2_1['Elapsed_days'] = df2_1.index-df2_1.index[0]
df1_1['DateN'] = date2num(pd.to_datetime(df1_1.index).tolist())
df2_1['DateN'] = date2num(pd.to_datetime(df2_1.index).tolist())

start2=datetime(2019,10, 1) 
end2=datetime(2020,3, 18)
df1_2=df1[start2:end2]
df2_2=df2[start2:end2]
df1_2['pct'] = df1_2['Close'].pct_change().cumsum()
df2_2['pct'] = df2_2['Close'].pct_change().cumsum()
df1_2['Elapsed_days'] = df1_2.index-df1_2.index[0]
df2_2['Elapsed_days'] = df2_2.index-df2_2.index[0]
df1_2['DateN'] = date2num(pd.to_datetime(df1_2.index).tolist())
df2_2['DateN'] = date2num(pd.to_datetime(df2_2.index).tolist())

%matplotlib inline
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(15,8),dpi=300)
ax1=plt.figtext(.1,.9,'Period over period charts for HUI, SP500')
ax1=plt.subplot2grid((12,1),(1,0),rowspan=5,colspan=1)
ax2=plt.subplot2grid((12,1),(6,0),rowspan=5,colspan=1, sharex=ax1)
ax3=plt.subplot2grid((12,1),(0,0),rowspan=1,colspan=1)
ax4=plt.subplot2grid((12,1),(11,0),rowspan=1,colspan=1, sharex=ax3)

ax1.xaxis.set_major_locator(years)
ax1.xaxis.set_major_formatter(years_fmt)
ax1.xaxis.set_minor_locator(months)

ax1.plot(df1_1.Elapsed_days,df1_1['pct'], label='HUI')
ax1.plot(df2_1.Elapsed_days,df2_1['pct'], label='SP500')
ax1.legend()
ax1.grid(True)
ax1.set_title('')

ax2.plot(df1_2.Elapsed_days,df1_2['pct'], label='HUI')
ax2.plot(df2_2.Elapsed_days,df2_2['pct'], label='SP500')
ax2.legend()
ax2.grid(True)
ax2.set_title('')

ax3.plot(df1_1.index,df1_1['Dividends'])
ax3.axes.yaxis.set_visible(False)
ax3.set_frame_on(False)

ax4.plot(df2_1.index,df2_1['Dividends'])
ax4.axes.yaxis.set_visible(False)
ax4.spines['top'].set_visible(False)
ax4.spines['right'].set_visible(False)
ax4.spines['left'].set_visible(False)

Tags: importdatetimeindexmatplotlibpltdayspddf1