Matplotlib教程


一、结构介绍

1️⃣容器层

容器层主要由Canvas, Figure, Axes组成。

Canvas主要是在最底层的系统层,可以放置画布的工具

FigureCanvas上的第一层,充当着画布的角色

Axes是第二层,相当于绘图区的角色

  • Figure 整个图形
  • Axes 绘图区域
  • Axis 坐标轴

一个图像可以包含多个绘图区(Axes),但一个Axes只能属于一个figure.

一个绘图区(坐标系)可以包含多个坐标轴

image-20220915110310589

2️⃣ 辅助显示层

除却图像外的内容,例如外观、边框线、坐标轴、坐标轴名称等等

3️⃣ 图像层

图像层指Axes内通过plot、scatter、bar、histogram、pie等函数绘制出的图像

image-20220915110623165

二、折线图与基本绘图功能

说起来,matplotlib.pyplot这玩意作用于当前图形(Figure)的当前坐标系(Axes)。

基本功能

1️⃣ 设置画布属性

1
plt.figure(figsize=(),dpi=)

2️⃣ 保存画布

1
plt.savefig(path)

3️⃣ 显示图像

1
plt.show() # 会释放资源,所以一定是在最后 

4️⃣ 添加刻度

1
2
3
4
5
6
plt.xticks(val,map)
plt.yticks(val,map)

# like
plt.xticks(x[::5],x_ticks_label[::5])
plt.yticks(y_ticks[::5])

5️⃣ 设置字体

1
2
#设置中文字体
plt.rcParams['font.sans-serif']=['SimHei']

6️⃣ 添加网络

1
plt.grid(True,linestyle="--",alpha=0.5)

7️⃣ 添加描述信息

1
2
3
plt.xlabel("时间") 
plt.ylabel("温度")
plt.title("中午11点0分到12点之间的温度变化图示")

8️⃣ 多次plot

1
2
3
4
# 绘制折线图 
plt.plot(x, y_shanghai, label="上海")
# 使⽤多次plot可以画多个折线
plt.plot(x, y_beijing, color='r', linestyle='--', label="北京")

9️⃣ 添加图例

1
2
# 显示图例 
plt.legend(loc="best")

关于图例:

Location String Location Code
‘best’ 0
‘upper right’ 1
‘upper left’ 2
‘lower left’ 3
‘lower right’ 4
‘right’ 5
‘center left’ 6
‘center right’ 7
‘lower center’ 8
‘upper center’ 9
‘center’ 10

关于风格:

颜色字符 风格字符
r 红色 - 实线
g 绿色 – 虚线
b 蓝色 -. 点划线
w 白色 :点虚线
c 青色 ‘’ 留空、空格
m 洋红
y 黄色
k 黑色

来看个栗子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import random
import matplotlib.pylab as plt

# 设置字体
plt.rcParams['font.sans-serif']=['SimHei']

# 创建数据
x=range(60)
y_shanghai=[random.uniform(15,18) for i in x]
y_beijing=[random.uniform(-5,5) for i in x]

# 创建画布
plt.figure(figsize=(20,8),dpi=100)

# 绘图
plt.plot(x,y_shanghai,label="上海",color="r",linestyle="--")
plt.plot(x,y_beijing,label="北京")

# 添加刻度
x_lables_ticks=["11点{}分".format(i) for i in x]
y_lables_ticks=range(-10,30)

plt.xticks(x[::5],x_lables_ticks[::5])
plt.yticks(y_lables_ticks[::5])

# 添加网格
plt.grid(linestyle="--",alpha=0.5)

# 添加描述信息
plt.xlabel("时间", fontsize=16)
plt.ylabel("温度", fontsize=16)
plt.title("某城市11点-12点温度变化", fontsize=20)

# 添加图例
plt.legend(loc="best")

# 显示
plt.show()
image-20220915113759811

🔟 在一个Figure上绘制多个Axes

当当当当,是我们的subplots函数哦

1
2
3
4
5
6
matplotlib.pyplot.subplots(nrows=1,ncols=1,**fig_kw)

'''
return : fig,axes
# axes是一个数组,存储了nrows*ncols个axes的内存地址
'''
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import random
import matplotlib.pylab as plt

# 设置字体
plt.rcParams['font.sans-serif']=['SimHei']

# 创建数据
x=range(60)
y_shanghai=[random.uniform(15,18) for i in x]
y_beijing=[random.uniform(-5,5) for i in x]

# 创建画布
fig,axes=plt.subplots(1,2,figsize=(20,8),dpi=80)

# 绘制
axes[0].plot(x,y_shanghai,label="上海")
axes[1].plot(x,y_beijing,label="北京",linestyle="--",color="r")

# 添加x,y轴刻度
x_ticks_label = ["11点{}分".format(i) for i in x]
y_ticks = range(40)

# 注意这里用set方法啦
axes[0].set_xticks(x[::5])
axes[0].set_yticks(y_ticks[::5])
axes[0].set_xticklabels(x_ticks_label[::5])

axes[1].set_xticks(x[::5])
axes[1].set_yticks(y_ticks[::5])
axes[1].set_xticklabels(x_ticks_label[::5])

# 添加网格

axes[0].grid(True, linestyle="--", alpha=0.5)
axes[1].grid(True, linestyle="--", alpha=0.5)

# 添加描述和标题
axes[0].set_xlabel("时间")
axes[0].set_ylabel("温度")
axes[0].set_title("上海中午11点--12点温度变化图", fontsize=25)

axes[1].set_xlabel("时间")
axes[1].set_ylabel("温度")
axes[1].set_title("北京中午11点--12点温度变化图", fontsize=25)

# 显示图例
axes[0].legend(loc=0)
axes[1].legend(loc=0)

# 显示
plt.show()
image-20220915123329995

三、常见图形

1️⃣ 折线图

特点:能够显示数据的变化趋势,反应事物的变化情况。

APIplt.plot()

2️⃣ 散点图

特点: 探寻事物间是否存在某种关联或者总结坐标点的分布模式,可以用于显示离群点(anomaly)

APIplt.scatter(x,y)

3️⃣ 柱状图

特点:探寻事物的分布模式,比较数据之间的差异,统计+对比

APIplt.bar(x,width)

4️⃣ 直方图

特点:绘制连续性的数据展示一组或多组数据的分布状况

APIplt.pyplot.hist(x,bins=None)

4️⃣ 饼图

特点:直观展现了不同数据的占比情况

APIplt.pie(x,labels=,autopct=,colors)

5️⃣绘制线条

1
2
3
4
for idx,m in enumerate(x):
# 绘制长条
# 从(m,y[idx])到(m,pre[idx])
plt.plot([m,m],[y[idx],pre[idx]],'g-')

注意,刻度一定要先画完图再添加刻度!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def Draw(EF,EF_i,EF_T,title="10:30"):
plt.figure(figsize=(8,6))
plt.xlim((Min:=min(EF_T)-1),(Max:=max(EF_T)+1))
plt.ylim(Min,Max)
x1, y1 = EF_T, EF
y2 = EF_i
plt.scatter(x1, y1, color="#ae040f", label="EF",edgecolors='black')
plt.scatter(x1,y2, c="#999c17", label="EF_imporve",edgecolors='black')
plt.plot([Min, Max], [Min, Max], linestyle="-", c="black", alpha=0.5)
plt.legend()
plt.grid(linestyle="--", alpha=0.5)
plt.xlabel("Measured daily LE without correction (W/m²)")
plt.ylabel("Estimated daily LE (W/m²)")
plt.title(title)
plt.show()

Draw([1,3,5,2,4],[2,1,5,4,3],[1,2,3,4,5])

image-20221217132143849