基本折线图(单变量,多变量)

一、单变量折线图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import pandas as pd
import matplotlib.pyplot as plt
#读取数据
ao = pd.read_csv("AO.txt",sep='\s+',header=None, names=['year','month','AO'])
ao_jan = ao[ao.month==1]
#创建Figure
fig = plt.figure(figsize=(10, 8))
#创建Axes
ax1 = fig.add_subplot(1,1,1)
#绘制折线图
ax1.plot(np.arange(1950,2020,1),ao_jan.AO, 'ko-')
#添加图题
ax1.set_title('1950-2019 January AO Index')
#添加y=0值水平参考线
ax1.axhline(0,ls=':',c='r')
#添加x=1990垂直参考线
ax1.axvline(1990,ls='--',c='g')
plt.show()

输出图形如下:

image-20200702161610554

其中数据格式如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
print(ao)
year month AO
0 1950 1 -0.060310
1 1950 2 0.626810
2 1950 3 -0.008128
3 1950 4 0.555100
4 1950 5 0.071577
.. ... ... ...
835 2019 8 -0.721770
836 2019 9 0.306200
837 2019 10 -0.082195
838 2019 11 -1.193400
839 2019 12 0.412070

[840 rows x 3 columns]

二、多变量折线图

实际上只是在同一个axes下叠加多个axes.plot()图层

1
2
3
4
5
6
7
8
9
10
11
12
13
import pandas as pd
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]
fig = plt.figure(figsize=(10, 8))
ax1 = fig.add_subplot(1,1,1)
ax1.plot(np.arange(1950,2020,1),ao_jan.AO,'ko-',label='Jan')
ax1.plot(np.arange(1950,2020,1),ao_feb.AO,'rs-',label='Feb')
ax1.set_title('1950-2019 AO Index')
ax1.legend()
plt.show()

image-20200702161610554

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