Python 使用matplotlib 畫數學公式圖與散點圖
阿新 • • 發佈:2019-01-08
import numpy as np import matplotlib.pyplot as plt x=np.linspace(0,10,1000) y=np.sin(x) z=cos(x^2) plt.figure(figsize=(8,4)) plt.plot(x,y,label='$sin(x)$',color='red',linewidth=3) plt.plot(x,z,'g--',label='$cos(x^2)$',lw=3) plt.xlabel('Time(s)') plt.ylabel('volt') plt.title('First python firgure') plt.ylim(-1.2,1.2) plt.legend() plt.show()
我們呼叫numpy的方法sin() 和 cos()
用linspace()得到1000個點。
linspace (起點,終點,元素個數)
<span style="font-size:14px;">plt.plot(x,y,label='$sin(x)$',color='red',linewidth=3)</span>
plot() 傳入點,標籤 和顏色
plt.xlabel('Time(s)')
plt.ylabel('volt')
傳入xy軸標籤
plt.title('First python firgure')
plt.ylim(-1.2,1.2)
設定圖片標題,和y軸範圍。
我們得到這樣的圖
畫散點圖是我們使用scatter()
#-*-coding:utf-8-* import matplotlib import matplotlib.pyplot as plt import numpy as np def file2matrix(filename): fr = open(filename) arrayOLines = fr.readlines() numberOfLines = len(arrayOLines) returnMat = np.zeros((numberOfLines,2)) classLabelVector = [] index =0 for line in arrayOLines: line = line.strip() listFormLine = line.split(' ') returnMat[index,:] = listFormLine[0:2] classLabelVector.append(int(listFormLine[-1])) index += 1 return returnMat, classLabelVector matrix, labels = file2matrix('Train.txt') print matrix print labels plt.figure(figsize=(8, 5), dpi=80) axes = plt.subplot(111) type1_x = [] type1_y = [] type2_x = [] type2_y = [] print 'range(len(labels)):' print range(len(labels)) for i in range(len(labels)): if labels[i] == 0: type1_x.append(matrix[i][0]) type1_y.append(matrix[i][1]) if labels[i] == 1: type2_x.append(matrix[i][0]) type2_y.append(matrix[i][1]) #print i, ':', labels[i], ':', type(labels[i]) type1 = axes.scatter(type1_x, type1_y,s=40, c='red' ) type2 = axes.scatter(type2_x, type2_y, s=40, c='green') W1 = 1.23924482 W2 = 1.59913719 B = -6.67130613 x = np.linspace(-4,10,200) y = (-W1/W2)*x+(-B/W2) axes.plot(x,y,'b',lw=3) #plt.scatter(matrix[:, 0], matrix[:, 1], s=20 * numpy.array(labels), # c=50 * numpy.array(labels), marker='o', # label='test') plt.xlabel('x1') plt.ylabel('x2') axes.legend((type1, type2), ('0', '1'),loc=1) plt.show()
我們從Train.txt得到資料。我們得到了這樣的圖