PythonStudy5

一、前言

在处理数据的时候需要考虑对数据属性的取舍. 除此之外, 还要对不同属性中有些偏离程度大的数据进行处理, 例如舍去那些偏离程度大的数据.

此时, 如果能够将数据通过图像的形式表现出来, 就能很好地完成上述工作.

另一方面就是, 每次需要代码时, 都是借用别人写好的代码. 自己没有理解到精髓, 想要对内容进行扩展自然也就成了问题.

二、画图

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

导入所需要的库, 第一行就是画图所需的库, 第二行是一个支持数组和矩阵运算的库, 底层由 C 实现, 运行速度很快.

1. 折线图

1
2
3
fig = plt.figure()
plt.plot([1,2,3,4],[1,4,9,16])
plt.show()

2. 直方图

1
2
3
fig = plt.figure(num=1, figsize=(8,6))
ax = fig.add_subplot(111)
ax.bar(x=np.arange(1,8,1), height=np.arange(10,80,10))

3. 散点图

1
2
3
4
5
6
7
8
x_values = [1,2,3,4,5]
y_values = [1,4,9,16,25]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x_values,y_values)

plt.show()

三、布局

1
2
3
fig = plt.figure(num=1,figsize=(4,4))
plt.plot([1,2,3,4],[1,2,3,4])
plt.show()

这种方式, 是先生成了一个画布, 然后在这个画布上隐式的生成一个画图区域来进行画图

1
2
3
4
fig = plt.figure(num=1,figsize=(4,4))
ax = fig.add_subplot(111)
ax.plot([1,2,3,4],[1,2,3,4])
plt.show()

这种方式, 先生成一个画布, 然后在此画布上, 选定一个子区域画了一个子图.

add_subplot 函数中的 111 指的是 1 行 1 列 第 1 个子图. 子图顺序是从左到右从上到下数的.

除了上面的方式, 还可以通过 plt 直接添加子图.

1
2
3
4
fig = plt.figure(num=1,figsize=(4,4))
plt.subplot(111)
plt.plot([1,2,3,4],[1,2,3,4])
plt.show()

结果是一样的.

有了这样的经验之后就可以在一张图中画出多个子图

1
2
3
4
5
6
7
8
9
10
11
fig = plt.figure(num=1,figsize=(4,4))
ax1 = fig.add_subplot(221)
ax1.plot([1,2,3,4],[1,2,3,4])
ax2 = fig.add_subplot(222)
ax2.plot([1,2,3,4],[2,2,3,4])
ax3 = fig.add_subplot(223)
ax3.plot([1,2,3,4],[1,2,2,4])
ax4 = fig.add_subplot(224)
ax4.plot([1,2,3,4],[1,2,3,3])

plt.show()

如果要画更复杂的图就需要把画布分割成一个网格. 然后让子

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

fig = plt.figure(num=1,figsize=(4,6))
gs = gridspec.GridSpec(3,3)

ax1 = fig.add_subplot(gs[0,:])
ax1.plot([1,2,3,4],[1,2,3,4])

ax2 = fig.add_subplot(gs[1,:-1])
ax2.plot([1,2,3,4],[1,2,3,4])

ax3 = fig.add_subplot(gs[1:,-1])
ax3.plot([1,2,3,4],[1,2,3,4])

ax4 = fig.add_subplot(gs[2,0])
ax4.plot([1,2,3,4],[1,2,3,4])

ax5 = fig.add_subplot(gs[2,1])
ax5.plot([1,2,3,4],[1,2,3,4])

plt.show()

四、总结

现在能画一些简单的图, 当然还可以很多可以学习的地方, 例如坐标轴的步长还有线的颜色和虚实.

需要的时候再来进行查找和补充吧!