机器学习代码基础(3)--Matplotlib速成

1.3Matplotlib速成

matplotlib是python中著名的2D绘图库,使用方法比较简单,按照以下三步操作就能很简单地完成绘图。 (1)调用plot(),scatter()等方法,并为绘图填充数据,数据是numpy的ndarray类型对象; (2)设定数据标签,使用xlabel()、ylabel()等方法 (3)展示绘图的结果,使用show()方法。

1.3.1绘制线条图

import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(0,2*np.pi,100)
Y = np.sin(X)
plt.plot(X,Y,'b')
#plt.plot(X,Y,'rs')
#plt.plot(X,Y,'g^')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.title('the curve of sin')
plt.show()
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(0,2*np.pi,100)
Y1 = np.sin(X)
Y2 = np.cos(X)
plt.plot(X,Y1,'b')
plt.plot(X,Y2,'r')
plt.axis([0,2*np.pi,-1,1])
#plt.plot(X,Y,'g^')
plt.show()
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(0,2*np.pi,100)
Y1 = np.sin(X)
Y2 = np.cos(X)
plt.plot(X,Y1,'b',label='sin(x)')
plt.plot(X,Y2,'r',label='cos(x)')
plt.axis([0,2*np.pi,-1,1])
plt.legend(loc='best')
plt.show()
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(0,2*np.pi,100)
Y1 = np.sin(X)
Y2 = np.cos(X)
plt.subplot(211)
plt.plot(X,Y1,'b',label='sin(x)')
plt.axis([0,2*np.pi,-1,1])
plt.subplot(212)
plt.plot(X,Y2,'r',label='cos(x)')
plt.axis([0,2*np.pi,-1,1])
plt.show()

1.3.2散点图

import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(0,6.28,100)
Y = np.sin(X)
plt.scatter(X,Y,c='red',marker='o')
#plt.plot(X,Y,'rs')
#plt.plot(X,Y,'g^')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.title('the curve of sin')
plt.show()

1.3.3直方图

import matplotlib.pyplot as plt
import numpy as np
data = np.random.randn(10000)
plt.hist(data,bins=30)
# 显示横轴标签
plt.xlabel("area")
# 显示纵轴标签
plt.ylabel("frequency")
# 显示图标题
plt.title("histgram")
plt.show()

1.3.4 饼图

labels = 'A','B','C','D'
sizes = [10,20,10,60]
plt.pie(sizes,labels=labels,explode = (0,0.1,0,0),autopct='%1.1f')
plt.show()

1.3.5雷达图

import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family']='SimHei'
matplotlib.rcParams['font.sans-serif']=['SimHei']
labels=np.array(['综合','第一周','第二周','第三周','第四周','第五周'])
nAttr=6
Python=np.array([88.7,85,90,95,70,96])
angles=np.linspace(0,2*np.pi,nAttr,endpoint=False)
Python=np.concatenate((Python,[Python[0]]))
angles=np.concatenate((angles,[angles[0]]))
fig=plt.figure(facecolor="white")
plt.subplot(111,polar=True)
plt.plot(angles,Python,'bo-',color='g',linewidth=2)
plt.fill(angles,Python,facecolor='g',alpha=0.2)
plt.thetagrids(angles*180/np.pi,labels)
plt.figtext(0.52,0.95,'python成绩分析图',ha='center')
plt.grid(True)
plt.savefig('dota_radar.JPG')
plt.show()
posted @ 2020-01-19 11:18  泰初  阅读(382)  评论(0编辑  收藏  举报