双y轴折线图

绘制双y轴折线图的要点在于将y轴的右轴变为一个兄弟轴(twin axis)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import matplotlib.pyplot as plt
import numpy as np
#读取数据
ao = pd.read_csv("AO.txt",sep='\s+',header=None, names=['year','month','AO'])
ao_jan = ao[ao.month==1]
ao_feb = ao[ao.month==2]
#创建Figure
fig = plt.figure()
#绘制单y轴折线图
ax1 = fig.add_subplot(1,1,1)
ax1.plot(np.arange(1950,2020,1),ao_jan.AO,'ko-',label='Jan')
ax1.set_ylabel('January',c='r')
ax1.set_title('1950-2019 AO Index')
#创建第二根y轴
ax2 = ax1.twinx()
ax2.plot(np.arange(1950,2020,1),ao_feb.AO,'rs-',label='Feb')
ax2.set_ylim(-4,4)
ax2.set_ylabel('February',c='k')

输出图形如下:

image-20200702161610554

测试数据下载地址:点此下载