本博文就是记录一些matplotlib的基本用法,方便日后查看.$ $
二维
利用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
| import numpy as np import matplotlib.pyplot as plt def loadData(): data=np.loadtxt('lr_linear_data.txt') xy=data[:,0:2] lable=data[:,2:] return xy, lable xy,lable=loadData() num=xy.shape[0] for i in xrange(num): if int(lable[i, 0]) == 0: plt.plot(xy[i, 0], xy[i, 1], 'ro') elif int(lable[i, 0]) == 1: plt.plot(xy[i, 0], xy[i, 1], 'bo') plt.axis([-6,6,-6,6]) plt.xlabel('x'); plt.ylabel('y') plt.show()
|
上面代码的显示结果如下:
利用matplotlib在二维平面画直线.
直线方程为:
\[
\theta_{0}+\theta_{1}x+\theta_{2}y=0
\]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import numpy as np import matplotlib.pyplot as plt theta=np.array([1.33761001,6.66484963,-6.63002026]) min_x = -6 max_x = 6 y_min_x = float(-theta[0] - theta[1] * min_x) / theta[2] y_max_x = float(-theta[0] - theta[1] * max_x) / theta[2] plt.plot([min_x, max_x], [y_min_x, y_max_x], '-g') plt.axis([-6,6,-6,6]) plt.xlabel('x'); plt.ylabel('y') plt.show()
|
显示结果:
三维
利用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
| from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np if __name__=='__main__': res = np.loadtxt('axis1_sample_point.txt') x=res[0:90,0:1] y=res[0:90,1:2] z=res[0:90,2:] ax=plt.subplot(111,projection='3d') ax.scatter(x[0:30],y[0:30],z[0:30],c='r') ax.scatter(x[30:60],y[30:60],z[30:60],c='y') ax.scatter(x[60:90],y[60:90],z[60:90],c='g') ax.set_zlabel('Z') ax.set_ylabel('Y') ax.set_xlabel('X') plt.show()
|
显示结果:
数据下载:Data