0%

Matplotlib库

1、安装

1
2
pip install matplotlib
apt-get install python-matplotlib

2、简单图形

matplotlib.pyplot.plot(*args, **kwargs)args代表输入数据,kwargs用于设置样式的参数。

方法 含义
matplotlib.pyplot.angle_spectrum 绘制电子波谱图
matplotlib.pyplot.bar 绘制柱状图
matplotlib.pyplot.barh 绘制直方图
matplotlib.pyplot.broken_barh 绘制水平直方图
matplotlib.pyplot.contour 绘制等高线图
matplotlib.pyplot.errorbar 绘制误差线
matplotlib.pyplot.hexbin 绘制六边形图案
matplotlib.pyplot.hist 绘制柱形图
matplotlib.pyplot.hist2d 绘制水平柱状图
matplotlib.pyplot.pie 绘制饼状图
matplotlib.pyplot.quiver 绘制量场图
matplotlib.pyplot.scatter 散点图
matplotlib.pyplot.specgram 绘制光谱图

1、折线图

1
2
3
4
5
# 折线图
def line_chart():
x = np.linspace(-2 * np.pi, 2 * np.pi, 1000)
y = np.sin(x)
plt.plot(x, y)

二维线形图常用设置(官方文档)

参数 含义
alpha= 设置线型的透明度,从 0.0 到 1.0
color= 设置线型的颜色
fillstyle= 设置线型的填充样式
linestyle= 设置线型的样式
linewidth= 设置线型的宽度
marker= 设置标记点的样式
…… ……
1
2


2、柱状图

1
2
3
4
5
6
# 柱形图
def column_chart():
x = [1, 2, 3]
y = [1, 2, 3]
plt.bar(x, y)
plt.show()

3、散点图

1
2
3
4
5
6
# 散点图
def scatter_chart():
x = np.random.ranf(10)
y = np.random.ranf(10)
plt.scatter(x, y)
plt.show()

散点图常用设置(官方文档)

参数 含义
s= 散点大小
c= 散点颜色
marker= 散点样式
cmap= 定义多类别散点的颜色
alpha= 点的透明度
edgecolors= 散点边缘颜色

4、饼状图

1
2
3
4
5
# 饼状图
def pie_chart():
x = [1, 2, 3, 4, 5]
plt.pie(x)
plt.show()

5、量场图

1
2
3
4
5
6
7
8
9
# 量场图
def quiver_chart():
x, y = np.mgrid[0:10, 0:10]
print(x.shape)
print(x)
print(y.shape)
print(y)
plt.quiver(x, y)
plt.show()

6、等高线图

1
2
3
4
5
6
7
8
# 等高线图
def contour_map():
x = np.linspace(-5, 5, 500)
y = np.linspace(-5, 5, 500)
X, Y = np.meshgrid(x, y)
Z = (1 - X / 2 + X ** 3 + Y ** 3) * np.exp(-X ** 2 - Y ** 2)
plt.contourf(X, Y, Z)
plt.show()

3、复杂图

1、组合图

将几种类型的一样的图放在一张图内显示。

1
2
3
4
5
6
7
8
9
import matplotlib.pyplot as plt

if __name__ == "__main__":
x = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
y_bar = [3, 4, 6, 8, 9, 10, 9, 11, 7, 8]
y_line = [2, 3, 5, 7, 8, 9, 8, 10, 6, 7]
plt.bar(x, y_bar)
plt.plot(x, y_line, '-o', color='y')
plt.show()

2、子图

1、把几张图形拼接在一起

figure 相当于绘画用的画板,而 axes 则相当于铺在画板上的画布。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import matplotlib.pyplot as plt
import numpy as np


if __name__ == "__main__":
# 生成数据
x = np.linspace(0, 10, 20)
y = x * x + 2
# 新建画板
fig = plt.figure()
# 向画板中添加画布,并指定位置
axes = fig.add_axes([0, 0, 1, 1])
# 在画布上绘制图像
axes.plot(x, y, 'r')
plt.show()
2、大图套小图
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


if __name__ == "__main__":
# 生成数据
x = np.linspace(0, 10, 20)
y = x * x + 2
# 新建画布
fig = plt.figure()
# 大画布
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
# 小画布
axes2 = fig.add_axes([0.25, 0.5, 0.4, 0.3])
# 绘制图像
axes1.plot(x, y, 'r')
axes2.plot(y, x, 'g')
plt.show()
3、 plt.subplots()用法
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
import matplotlib.pyplot as plt
import numpy as np


def draw_1(x, y):
# 创建画板和画布
fig, axes = plt.subplots()
# 绘制图形
axes.plot(x, y, 'r')


def draw_2(x, y):
# 创建画板和画布(1行2列)
fig, axes = plt.subplots(nrows=1, ncols=2)
# 绘制图形
for ax in axes:
ax.plot(x, y, 'r')


def draw_3(x, y):
# 创建画板和画布
# 通过 figsize 调节尺寸, dpi 调节显示精度
fig, axes = plt.subplots(figsize=(16, 9), dpi=50)
# 绘制图形
axes.plot(x, y, 'r')


if __name__ == "__main__":
# 生成数据
x = np.linspace(0, 10, 20)
y = x * x + 2

# draw_1(x, y)
# draw_2(x, y)
draw_3(x, y)

plt.show()

4、规范绘图

1、添加图标题、图例

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
import matplotlib.pyplot as plt
import numpy as np


if __name__ == "__main__":
# 生成数据
x = np.linspace(0, 10, 20)
y = x * x + 2

fig, axes = plt.subplots()
# 横轴名称
axes.set_xlabel('x label')
# 纵轴名称
axes.set_ylabel('x label')
# 图标题
axes.set_title('title')
# 绘制图像
axes.plot(x, x ** 2)
axes.plot(x, x ** 3)
# 图例
axes.legend(['y=x^2', 'y=x^3'], loc=0)
# 图例中的 loc 参数标记图例位置,
# 1,2,3,4 依次代表:右上角、左上角、左下角,右下角;
# 0 代表自适应

plt.show()

2、线型、颜色、透明度

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 matplotlib.pyplot as plt
import numpy as np


if __name__ == "__main__":
# 生成数据
x = np.linspace(0, 10, 20)
y = x * x + 2

fig, axes = plt.subplots()

# alpha 用于设置透明度[0,1]
axes.plot(x, x + 1, color='red', alpha=0.3)

# linewidth 用于设置线的宽度
axes.plot(x, x + 2, color='#1155dd', linewidth=1.0)

# 虚线
# linestyle 和 ls 用于设置虚线类型
# 取值有['-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted']
# lw 用于设置虚线交错宽度
axes.plot(x, x + 3, color='r', lw=2, linestyle='--')
axes.plot(x, x + 4, color='g', lw=1.5, ls=':')

# 符号
# marker 取值:['+','o','s','1',]
# markersize 用于设置符号大小
# markerfacecolor 用于设置符号颜色
# markeredgewidth 用于设置符号边框宽度
# markeredgecolor 用于设置符号边框颜色
axes.plot(x, x + 5, color='b', lw=2, ls=':', marker='1')
axes.plot(x, x + 6, color='b', lw=2, ls='--',
marker='s', markersize=8, markerfacecolor='r')
axes.plot(x, x + 7, color="purple", lw=1, ls='-', marker='s',
markersize=8, markerfacecolor="yellow",
markeredgewidth=2, markeredgecolor="blue")

plt.show()

3、画布网格、坐标轴范围

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import matplotlib.pyplot as plt
import numpy as np


if __name__ == "__main__":
# 生成数据
x = np.linspace(0, 10, 20)
y = x * x + 2

fig, axes = plt.subplots(1, 2, figsize=(10, 5))

# 显示网格
axes[0].plot(x, x**2, x, x**3, lw=2)
axes[0].grid(True)

# 设置坐标轴范围
axes[1].plot(x, x**2, x, x**3)
axes[1].set_ylim([0, 60])
axes[1].set_xlim([2, 5])

plt.show()

4、图形标注

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
import matplotlib.pyplot as plt
import numpy as np


def draw_1(x_bar, y_bar):
fig, axes = plt.subplots()
bars = axes.bar(x_bar, y_bar, color='blue', label=x_bar, width=2) # 绘制柱形图
for i, rect in enumerate(bars):
x_text = rect.get_x() # 获取柱形图横坐标
y_text = rect.get_height() + 0.01 # 获取柱子的高度并增加 0.01
plt.text(x_text, y_text, '%.1f' % y_bar[i]) # 标注文字


def draw_2(x_bar, y_bar):
fig, axes = plt.subplots()
bars = axes.bar(x_bar, y_bar, color='blue', label=x_bar, width=2) # 绘制柱形图
for i, rect in enumerate(bars):
x_text = rect.get_x() # 获取柱形图横坐标
y_text = rect.get_height() + 0.01 # 获取柱子的高度并增加 0.01
plt.text(x_text, y_text, '%.1f' % y_bar[i]) # 标注文字

# 增加箭头标注
plt.annotate('Min', xy=(32, 0.3), xytext=(36, 0.3),
arrowprops=dict(facecolor='black', width=1, headwidth=7))


if __name__ == "__main__":
# 生成数据
x_bar = [10, 20, 30, 40, 50] # 柱形图横坐标
y_bar = [0.5, 0.6, 0.3, 0.4, 0.8] # 柱形图纵坐标

# 柱形图文字标注
# draw_1(x, y)
# 添加箭头标注
draw_2(x_bar, y_bar)

plt.show()

5、小试牛刀

使用Matplotlib绘制下面的图案

小试牛刀

参考答案:

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
# -----------------------------------------------------------------------------
# Copyright (c) 2015, Nicolas P. Rougier. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(8, 5), dpi=80)
ax = plt.subplot(111)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)

plt.plot(X, C, color="blue", linewidth=2.5,
linestyle="-", label="Cos Function")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="Sin Function")

plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])

plt.ylim(C.min() * 1.1, C.max() * 1.1)
plt.yticks([-1, +1],
[r'$-1$', r'$+1$'])

t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)],
color='blue', linewidth=1.5, linestyle="--")
plt.scatter([t, ], [np.cos(t), ], 50, color='blue')
plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
xy=(t, np.sin(t)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

plt.plot([t, t], [0, np.sin(t)],
color='red', linewidth=1.5, linestyle="--")
plt.scatter([t, ], [np.sin(t), ], 50, color='red')
plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',
xy=(t, np.cos(t)), xycoords='data',
xytext=(-90, -50), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

plt.legend(loc='upper left', frameon=False)
plt.show()

遇到的问题

1、中文乱码

在py脚本中添加下列代码

1
2
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']

0、参考

Matolotlib官网

Matplotlib 中文

Matplotlib 数据绘图基础课程