matplotlib1
零、准备工作
1 | import numpy as np |
- mat → MATLAB
plot → 做图
lib → 库
提供了强大的可视化功能 - 作图要有自变量、因变量、函数
一、折线图
- 作图基本操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23x = np.arange(100)
y = 2*x + 1
plt.plot(x,y)
# 即可输出图像,但可视化效果并不好
# 图像美化
x = np.arange(100)
y1 = 2*x + 1
y2 = -2*x - 1 # 多曲线
plt.figure(figsize=(12,6)) # 设定图像大小
plt.plot(x,y1,'-.',color='r',linewidth=6) # 设定线的样式
plt.plot(x,y2,'-.',color='r',linewidth=6) # 多条曲线
plt.xlabel('independent variable',fontsize=16) # 横坐标名称
plt.ylabel('dependent variable',fontsize=16) # 纵坐标
plt.xticks(fontsize=12) # 数字大小
plt.yticks(...)
plt.legend(['line1','line2'],fontsize=12) # 图例,按顺序来
plt.title('xxx',fontsize=12) # 图像名字
plt.grid() # 网格
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48x = np.arange(100)
y1 = 2*x + 1
y2 = -2*x - 1
plt.figure(figsize=(12,6))
plt.subplot(2,2,1) # 做子图,两行一列,最后一格数字是“接下来画的图在第一个画布里”
plt.plot(x,y1,'-.',color='r',linewidth=6)
plt.xlabel('independent variable',fontsize=16)
plt.ylabel('dependent variable',fontsize=16)
plt.xticks(fontsize=12)
plt.yticks(...)
plt.legend(['line1'],fontsize=12)
plt.title('xxx',fontsize=12)
plt.grid()
plt.subplot(2,2,2) # 接下来做第二张图
plt.plot(x,y2,'-.',color='b',linewidth=6)
plt.xlabel('independent variable',fontsize=16)
plt.ylabel('dependent variable',fontsize=16)
plt.xticks(fontsize=12)
plt.yticks(...)
plt.legend(['line2'],fontsize=12)
plt.title('xxx',fontsize=12)
plt.grid()
xx == np.arange(-6,6,0.01) # 保证曲线的取点够多,图像够平滑
plt.subplot(2,2,3)
plt.plot(xx,np.sin(xx),'-.',color='g',linewidth=6)
plt.xlabel('independent variable',fontsize=16)
plt.ylabel('dependent variable',fontsize=16)
plt.xticks(fontsize=12)
plt.yticks(...)
plt.legend(['line3'],fontsize=12)
plt.title('xxx',fontsize=12)
plt.grid()
plt.subplot(2,2,4)
plt.plot(xx,np.cos(xx),'-.',color='y',linewidth=6)
plt.xlabel('independent variable',fontsize=16)
plt.ylabel('dependent variable',fontsize=16)
plt.xticks(fontsize=12)
plt.yticks(...)
plt.legend(['line4'],fontsize=12)
plt.title('xxx',fontsize=12)
plt.grid()
plt.show() # 只写一遍就可以
二、条形图
1 | Company = ['Samsung','Huawei','Apple','Xiaomi','OPPO','VIVO','Others'] |
三、直方图
- 频数,适合表示频率
1
2
3
4
5
6
7
8
9
10
11x = np.random.randint(1,11,10) # 生成一个随机一行数组备用
plt.figure(figsize=(12,6))
plt.hist(x,color = 'royalblue') # 生成频数直方图。
plt.show()
# 正态分布直方图
x = np.random.randn(100,1) # 生成的数字越多,越接近正态分布
plt.figure(figsize=(12,6))
plt.hist(x,color = 'royalblue',bins = 100) # 生成频数直方图。bins越大,越接近平滑。
plt.show()
四、饼图
- 适合表示百分比
1
2
3
4
5
6
7
8data['share'] = [i/data.Shipment.sum().round(3) for i in data.Shipment] # 保留三位小数
x = data.Company
y = data.Share
plt.figure(figsize=(6,6)) # 改成圆形
plt.pie(y,labels = x,autopct = '%.1f%%',textprop = {'fontsize':'x-large'},labeldistance = 1.2,shadow = True) # 以百分比形式表示,数字大小,名称距离,阴影
plt.show()