每一次写程序为了可视化都避不开 Python 的 matplotlib,干脆整理一下这个东西。以防后面每次需要反复查一样的东西。

绘图基础

导入步骤

1
2
import matplotlib.pyplot as plt 
import numpy as np

基本操作

1
2
3
4
5
6
7
8
9
10
11
12
plt.show()
plt.clr() #清空
plt.savefig() #保存
```

**绘制**:

```python
plt.plot(x, y, label = 'name', color = 'blue', linestyle = '--')
plt.xlabel('Time')
plt.ylabel('Acc')
plt.legend(loc = 'upper left')

关于上面的位置,有下表:

位置
upper right 右上
lower left 左下
center center

排列组合……

特殊图

混淆矩阵绘制

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

def plot_confusion_matrix(cm, savename, title='Confusion Matrix'):

plt.figure(figsize=(12, 8), dpi=100)
np.set_printoptions(precision=2)

# 在混淆矩阵中每格的概率值
ind_array = np.arange(len(classes))
x, y = np.meshgrid(ind_array, ind_array)
for x_val, y_val in zip(x.flatten(), y.flatten()):
c = cm[y_val][x_val]
if c > 0.001:
plt.text(x_val, y_val, "%0.0f" % (c,), color='red', fontsize=15, va='center', ha='center')

plt.imshow(cm, interpolation='nearest', cmap=plt.cm.binary)
plt.title(title)
plt.colorbar()
xlocations = np.array(range(len(classes)))
plt.xticks(xlocations, classes, rotation=90)
plt.yticks(xlocations, classes)
plt.ylabel('Actual label')
plt.xlabel('Predict label')

# offset the tick
tick_marks = np.array(range(len(classes))) + 0.5
plt.gca().set_xticks(tick_marks, minor=True)
plt.gca().set_yticks(tick_marks, minor=True)
plt.gca().xaxis.set_ticks_position('none')
plt.gca().yaxis.set_ticks_position('none')
plt.grid(True, which='minor', linestyle='-')
plt.gcf().subplots_adjust(bottom=0.15)

# show confusion matrix
plt.savefig(savename, format='png')
plt.show()

子图

1
2
3
4
5
plt.subplot(221)
plt.plot(x1, y1)
plt.subplot(222)
plt.plot(x2, y2)
plt.show()

热力图

1
plt.imshow(matrix)