一次性掌握所有 Python 画图基础操作
p y t h o n python python 画图介绍
本文以实用为第一目标,保证读者在看完此文之后可以迅速上手 p y t h o n python python 画图,掌握所有画图的基本技巧。(收藏的同时点个赞呗ヽ(·̀ω·́ )ゝ)
如果你对这篇文章可感兴趣,可以点击「【访客必读 - 指引页】一文囊括主页内所有高质量博客」,查看完整博客分类与对应链接。
库加载
我们使用 matplotlib
来进行 p y t h o n python python 画图,具体的库加载以及初始设置代码如下所示。
import numpy as np# 加载数学库用于函数描述 import matplotlib import matplotlib.pyplot as plt from matplotlib import style matplotlib.rcParams['text.usetex'] = True # 开启Latex风格 plt.figure(figsize=(10, 10), dpi=70) # 设置图像大小 # style.use('ggplot') # 加载'ggplot'风格 # f, ax = plt.subplots(1, 3) # 设置子图
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
每一段代码都有注释,可以根据注释把握每行代码的内容。看不懂也没有关系,先把代码加上,继续往下看即可。
p y t h o n python python 画图的原理
其实原理非常简单,就是给出一个横坐标的 l i s t list list,再给出一个对应的纵坐标 l i s t list list,然后设置点大小、点外框大小、线大小、点颜色、线颜色、点形状、线形状、标题、标签即可。设置部分的内容看起来很多,但其实也可以不用设置,不设置就代表使用默认的大小、形状以及颜色。
除此之外,画图最主要的分类就是画点还是将点连线,如果使用 scatter
函数,则将散点画在图中;如果使用 plot
函数,则会将散点连线,在下文中,读者将会更深刻地感受到这一点。
图像加载
# plt.tight_layout() # 当有多个子图时,可以使用该语句保证各子图标题不会重叠
# plt.savefig('myplot1.pdf', dpi=700) # dpi 表示以高分辨率保存一个图片文件,pdf为文件格式,输出位图文件
plt.show() # 渲染图片
1
2
3
1
2
3
上述的代码中主要就是
plt.show()
语句,其余语句都是一些其余设置,看注释即可明白。
画图分类
python
中画图主要分为下述几类。
- 画单点
- 画散点
- 画散点连线
- 画函数
主要涉及到的一些 操作
分为下述几类。
- 子图
- 设置横纵坐标范围
- 图像标题
- 图像中画图类型的标签
画单点
画单点比较简单,给出下述代码以及返回结果即可掌握。(需要加入最开头给出的初始设置内容)
def main(): X = 1 Y = 100 plt.scatter(X, Y, s=50)// s为点大小 plt.show()
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5

上图是加载了 style.use('ggplot')
该风格后的效果,如果去掉该行,输出将如下所示。

读者可以根据自己的喜好选择该风格,也可以去搜索其他的风格,下文接下来的示例将均使用 'ggplot'
风格进行展示。
画散点
知道了画单点的方法之后,画散点就变得非常简单,因为我们只需要将单点中传入的单变量改成一个 l i s t list list 即可,具体代码和效果如下所示。
def main():
X, Y = [], []
for i in range(1, 10):
X.append(i)
Y.append(np.sin(i))
plt.scatter(X, Y, s=50)
plt.show()
1
2
3
4
5
6
7
1
2
3
4
5
6
7

散点连线
只有散点,通常会使得图像变得不够直观,因此我们使用
plot
函数将所有散点连在一起,具体操作如下所示。
def main(): X, Y = [], [] for i in range(1, 10): X.append(i) Y.append(np.sin(i)) plt.scatter(X, Y, s=50) plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7

我们也可以对 plot
函数进行设置,即可输出如下所示图形。
def main():
X, Y = [], []
for i in range(1, 10):
X.append(i)
Y.append(np.sin(i))
plt.plot(X, Y, '-p', color='grey',
marker = 'o',
markersize=8, linewidth=2,
markerfacecolor='red',
markeredgecolor='grey',
markeredgewidth=2)
plt.show()
1
2
3
4
5
6
7
8
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12

可以看到我们对于点大小、颜色、点外框颜色、大小以及线颜色、线宽均进行了设置,读者可以自行选择设置选项进行尝试。
画函数
尽管散点连线了,但是由于散点的密度不够大,因此我们可以进一步的使用
只有散点,通常会使得图像变得不够直观,因此我们使用 plot
函数将所有散点连在一起,具体操作如下所示。
def main(): X = np.linspace(1, 10, 100)# 将[1,10]区间均分为100个点,得到100个横坐标 Y = np.sin(X) # 求出100个点的纵坐标 plt.plot(X, Y, color='red', linewidth=1.0, linestyle='-') # 将100个散点连在一起 plt.show()
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5

线条形状、颜色、标签
在画函数中我们可以设置线条形状 linestyle
、线条宽度 linewidth
以及线条颜色 color
。我们接下来介绍常见的几种线条形状以及如何给线条加上标签,并给出具体的代码供读者参考。
def main():
X = np.linspace(1, 10, 100)
Y1 = np.sin(X)
Y2 = np.cos(X)
Y3 = -X
Y4 = X
plt.plot(X, Y1, color='lightcoral', linewidth=3.0, linestyle='-', label='-')
plt.plot(X, Y2, color='burlywood', linewidth=3.0, linestyle='--', label='--')
plt.plot(X, Y3, color='mediumturquoise', linewidth=3.0, linestyle='-.', label='-.')
plt.plot(X, Y4, color='mediumpurple', linewidth=3.0, linestyle=':', label=':')
plt.legend(loc='best') # 把标签加载到图中哪个位置
plt.show()
1
2
3
4
5
6
7
8
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12
常见的
linestyle
还有 '-', '--', '-.', ':', 'solid', 'dashed', 'dashdot', 'dotted'
,读者可以自行尝试。
常见的 legend
的 loc
位置还有 best, upper right, upper left, lower left, lower right, right, center left, center right, lower center, upper center, center
,其中 best
表示将标签加载到 python
认为最佳的位置。

支持 Latex 的标签
由于是函数作图,因此我们通常会将标签设置为线条所代表的函数值,因此我们需要介绍支持 Latex 的标签。我们将 label
的数值设置为 r'$x_n$'
即可支持 L a t e x Latex Latex,如下图所示。
def main(): X = np.linspace(0, 1, 100) Y1 = np.sqrt(X) Y2 = X Y3 = X * X Y4 = X * X * X plt.plot(X, Y1, color='lightcoral', linewidth=3.0, linestyle='-', label=r'$y_1=\sqrt{x}$') plt.plot(X, Y2, color='burlywood', linewidth=3.0, linestyle='--', label=r'$y_2=x$') plt.plot(X, Y3, color='mediumturquoise', linewidth=3.0, linestyle='-.', label=r'$y_3=x^2$') plt.plot(X, Y4, color='mediumpurple', linewidth=3.0, linestyle=':', label=r'$y_4=x^3$') plt.legend(loc='best') plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12

设置横纵坐标标号以及图像标题
最后我们需要介绍如何给该图像设置横纵坐标、范围以及标题。我们首先不设置范围,则具体代码以及输出图形如下。
def main():
X = np.linspace(0, 1, 100)
Y1 = np.sqrt(X)
Y2 = X
Y3 = X * X
Y4 = X * X * X
plt.plot(X, Y1, color='lightcoral', linewidth=3.0, linestyle='-', label=r'$y_1=\sqrt{x}$')
plt.plot(X, Y2, color='burlywood', linewidth=3.0, linestyle='--', label=r'$y_2=x$')
plt.plot(X, Y3, color='mediumturquoise', linewidth=3.0, linestyle='-.', label=r'$y_3=x^2$')
plt.plot(X, Y4, color='mediumpurple', linewidth=3.0, linestyle=':', label=r'$y_4=x^3$')
plt.legend(loc='best')
# x、y坐标以及标题
plt.xlabel('x', fontsize=18)
plt.ylabel('y', fontsize=18)
plt.title(r'$f(x)=\sqrt{x},x,x^2,x^3$', fontsize=18)
plt.show()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

设置横纵坐标的范围
有的时候我们会觉得系统默认的横纵坐标范围不合适,因此我们需要自行设置横纵坐标,具体代码以及结果如下所示。
def main(): X = np.linspace(0, 2, 100) Y1 = np.sqrt(X) Y2 = X Y3 = X * X Y4 = X * X * X plt.plot(X, Y1, color='lightcoral', linewidth=3.0, linestyle='-', label=r'$y_1=\sqrt{x}$') plt.plot(X, Y2, color='burlywood', linewidth=3.0, linestyle='--', label=r'$y_2=x$') plt.plot(X, Y3, color='mediumturquoise', linewidth=3.0, linestyle='-.', label=r'$y_3=x^2$') plt.plot(X, Y4, color='mediumpurple', linewidth=3.0, linestyle=':', label=r'$y_4=x^3$') plt.legend(loc='best') # x、y坐标以及标题 plt.xlabel('x', fontsize=18) plt.ylabel('y', fontsize=18) plt.title(r'$f(x)=\sqrt{x},x,x^2,x^3$', fontsize=18) # 设置坐标范围 plt.ylim(-1, 4) plt.xlim(-1, 4) plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21

给函数中的一个点标号
当函数比较复杂的时候,我们往往需要对关键点进行标号,通常使用的方式是加箭头或者不加,我们先给出加箭头的代码以及结果。
def main():
X = np.linspace(0, 1, 100)
Y1 = np.sqrt(X)
Y2 = X
Y3 = X * X
Y4 = X * X * X
plt.plot(X, Y1, color='lightcoral', linewidth=3.0, linestyle='-', label=r'$y_1=\sqrt{x}$')
plt.plot(X, Y2, color='burlywood', linewidth=3.0, linestyle='--', label=r'$y_2=x$')
plt.plot(X, Y3, color='mediumturquoise', linewidth=3.0, linestyle='-.', label=r'$y_3=x^2$')
plt.plot(X, Y4, color='mediumpurple', linewidth=3.0, linestyle=':', label=r'$y_4=x^3$')
plt.legend(loc='best')
# x、y坐标以及标题
plt.xlabel('x', fontsize=18)
plt.ylabel('y', fontsize=18)
plt.title(r'$f(x)=\sqrt{x},x,x^2,x^3$', fontsize=18)
# 关键点标号
plt.scatter(1, 1, s=100)
plt.ylim(-1, 2)
plt.annotate('End Point', fontsize=20,
xy=(1, 1), xycoords='data',
xytext=(0.8, 0.95), textcoords='axes fraction',
arrowprops=dict(facecolor='black', shrink=0.1),
horizontalalignment='right', verticalalignment='top')
plt.show()
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
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
其中
xy(1,1)
表示关键点的位置,xycoords='data'
表示关键点坐标所采用的坐标方式, shrink
参数表示箭头距离关键点的距离,horizontalalignment='right', verticalalignment='top'
均表示注释的位置。

也可以使用不加箭头的方式,即将上述 annotate
换成下述代码即可。
# 关键点标号 plt.scatter(1, 1, s=100) plt.ylim(-0.1, 1.3) plt.xlim(-0.1, 1.3) plt.annotate('End Point', xy=(1.05, 1.05), fontsize=20, xycoords='data')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8

色卡
当绘制多个函数时,会发现颜色的设计非常难把握,因此下图给出一张色卡供颜色选择。

子图
最后是如何用 python
画子图,其实画子图就是将上述的 p l t plt plt 换成 a x ax ax,具体操作的思路与之前的操作并没有太大的区别,接下来给出一个包含横纵坐标、函数坐标、标题的完整子图代码,读者可以从代码中获取相应操作的代码。

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot') # 加载'ggplot'风格
matplotlib.rcParams['text.usetex'] = True # 开启Latex风格
plt.figure(figsize=(10, 10), dpi=70) # 设置图像大小
f, ax = plt.subplots(2, 2) # 设置子图
def func1():
X = np.linspace(0, 1, 100)
Y1 = np.sqrt(X)
# ax[0][0]的设置
ax[0][0].plot(X, Y1, color='lightcoral', linewidth=3.0, linestyle='-', label=r'$y_1=\sqrt{x}$')
ax[0][0].set_xlabel('x', fontsize=10)
ax[0][0].set_ylabel('y', fontsize=10)
ax[0][0].set_title(r'$f(x)=\sqrt{x}$', fontsize=16)
ax[0][0].legend(loc='best')
# ax[0][0]关键点
ax[0][0].scatter(0.5, np.sqrt(0.5), s=100)
ax[0][0].annotate('End Point',
xy=(0.6, 0.5),
fontsize=12,
xycoords='data')
def func2():
X = np.linspace(0, 1, 100)
Y2 = X
# ax[0][1]的设置
ax[0][1].plot(X, Y2, color='burlywood', linewidth=3.0, linestyle='--', label=r'$y_2=x$')
ax[0][1].set_xlabel('x', fontsize=10)
ax[0][1].set_ylabel('y', fontsize=10)
ax[0][1].set_title(r'$f(x)=x$', fontsize=16)
ax[0][1].legend(loc='best')
# ax[0][1]关键点
ax[0][1].scatter(0.5, 0.5, s=100)
ax[0][1].annotate('End Point',
fontsize=12,
xytext=(0.7, 0.1),
xy=(0.5, 0.5),
xycoords='data',
arrowprops=dict(facecolor='gray', shrink=0.15))
def func3():
X = np.linspace(0, 1, 100)
Y3 = X * X
# ax[1][0]的设置
ax[1][0].plot(X, Y3, color='mediumturquoise', linewidth=3.0, linestyle='-.', label=r'$y_3=x^2$')
ax[1][0].set_xlabel('x', fontsize=10)
ax[1][0].set_ylabel('y', fontsize=10)
ax[1][0].set_title(r'$f(x)=x^2$', fontsize=16)
ax[1][0].legend(loc='best')
# ax[1][0]关键点
ax[1][0].scatter(0.5, 0.5 * 0.5, s=100)
ax[1][0].annotate('End Point',
fontsize=12,
xytext=(0.05, 0.6),
xy=(0.5, 0.5 * 0.5),
xycoords='data',
arrowprops=dict(facecolor='black', shrink=0.1))
def func4():
X = np.linspace(0, 1, 100)
Y4 = X * X * X
# ax[1][1]的设置
ax[1][1].plot(X, Y4, color='mediumpurple', linewidth=3.0, linestyle=':', label=r'$y_4=x^3$')
ax[1][1].set_xlabel('x', fontsize=10)
ax[1][1].set_ylabel('y', fontsize=10)
ax[1][1].set_title(r'$f(x)=x^3$', fontsize=16)
ax[1][1].legend(loc='best')
# ax[1][1]关键点
ax[1][1].scatter(0.5, 0.5 * 0.5 * 0.5, s=100)
ax[1][1].annotate('End Point',
xy=(0.2, 0.3),
fontsize=12,
xycoords='data')
def main():
func1()
func2()
func3()
func4()
plt.tight_layout() # 当有多个子图时,可以使用该语句保证各子图标题不会重叠
plt.savefig('myplot1.pdf', dpi=700) # dpi 表示以高分辨率保存一个图片文件,pdf为文件格式,输出位图文件
plt.show()
if __name__ == '__main__':
main()
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
后记
上述所涉及的内容即为 p y t h o n python python 应用
matplotlib
画图的基本操作了,如果想要进一步的深化画图能力,推荐根据需求在 matplotlib
官方文档 中进行搜索。祝大家在 python
画图的路上更进一步!💪💪💪