Matplotlib可视化

画直线图

import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.ylabel('some numbers')
plt.show()

 基本画图

 1 import numpy as np
 2 import matplotlib.pyplot as plt
 3 from pylab import *
 4 
 5 # 定义数据部分
 6 x = np.arange(0., 10, 0.2)
 7 y1 = np.cos(x)
 8 y2 = np.sin(x)
 9 y3 = np.sqrt(x)
10 
11 # 绘制 3 条函数曲线
12 plt.plot(x, y1, color='blue', linewidth=1.5, linestyle='-', marker='.', label=r'$y = cos{x}$')
13 plt.plot(x, y2, color='green', linewidth=1.5, linestyle='-', marker='*', label=r'$y = sin{x}$')
14 plt.plot(x, y3, color='m', linewidth=1.5, linestyle='-', marker='x', label=r'$y = \sqrt{x}$')
15 
16 # 坐标轴上移
17 ax = plt.subplot(111)
18 ax.spines['right'].set_color('none')     # 去掉右边的边框线
19 ax.spines['top'].set_color('none')       # 去掉上边的边框线
20 
21 # 移动下边边框线,相当于移动 X 轴
22 ax.xaxis.set_ticks_position('bottom')
23 ax.spines['bottom'].set_position(('data', 0))
24 
25 # 移动左边边框线,相当于移动 y 轴
26 ax.yaxis.set_ticks_position('left')
27 ax.spines['left'].set_position(('data', 0))
28 
29 # 设置 x, y 轴的取值范围
30 plt.xlim(x.min()*1.1, x.max()*1.1)
31 plt.ylim(-1.5, 4.0)
32 
33 # 设置 x, y 轴的刻度值
34 plt.xticks([2, 4, 6, 8, 10], [r'2', r'4', r'6', r'8', r'10'])
35 plt.yticks([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0],
36     [r'-1.0', r'0.0', r'1.0', r'2.0', r'3.0', r'4.0'])
37 
38 # 添加文字
39 plt.text(4, 1.68, r'$x \in [0.0, \ 10.0]$', color='k', fontsize=15)
40 plt.text(4, 1.38, r'$y \in [-1.0, \ 4.0]$', color='k', fontsize=15)
41 
42 # 特殊点添加注解
43 plt.scatter([8,],[np.sqrt(8),], 50, color ='m')  # 使用散点图放大当前点
44 plt.annotate(r'$2\sqrt{2}$', xy=(8, np.sqrt(8)), xytext=(8.5, 2.2), fontsize=16, color='#090909', arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=0.1', color='#090909'))
45 
46 # 设置标题、x轴、y轴
47 plt.title(r'$the \ function \ figure \ of \ cos(), \ sin() \ and \ sqrt()$', fontsize=19)
48 plt.xlabel(r'$the \ input \ value \ of \ x$', fontsize=18, labelpad=88.8)
49 plt.ylabel(r'$y = f(x)$', fontsize=18, labelpad=12.5)
50 
51 # 设置图例及位置
52 plt.legend(loc='upper left')
53 # plt.legend(['cos(x)', 'sin(x)', 'sqrt(x)'], loc='up right')
54 
55 # 显示网格线
56 plt.grid(True)
57 
58 # 显示绘图
59 plt.show()
60 #保存
61 #plt.savefig()
View Code

常用图形

曲线图:

x=np.arange(-5,5,0.1)
y=x ** 2
plt.plot(x,y)
plt.show()

 

灰度图

import matplotlib.pyplot as plt
import numpy as np
x=np.random.normal(size=1000)
plt.hist(x,bins=10)
plt.show()

散点图:

import matplotlib.pyplot as plt
import numpy as np
x=np.random.normal(size=1000)
y=np.random.normal(size=1000)
plt.scatter(x,y)
plt.show()

箱式图:

 

import matplotlib.pyplot as plt
import numpy as np
x=np.random.normal(size=1000)
plt.boxplot(x)
plt.show()

 

posted @ 2018-03-03 11:30  88aa123  阅读(151)  评论(0编辑  收藏  举报