目的:
练习使用Matplotlib进行函数图像的绘制等数据处理任务。
题目:
一:实现函数图像的绘制
import numpy as np
import matplotlib.pyplot as plt
#import seaborn as sns
x = np.linspace (0,2,1000) #interval
#make it the function
y = np.exp( -1*(x**2) )
y *= (x-2)
y = np.sin(y) * np.sin(y)
plt.plot(x,y) # plot it
plt.plot( x , y ,color ='red', label = 'hello' ) # label for fun
plt.xlabel('x') #set the label
plt.ylabel('y')
plt.title( 'my_function:' ) #set the title
plt.legend() #show these title and label together
plt.show()
相应图像:
二:数据拟合(最小二乘拟合)
题目
相应代码:
import numpy as np
import matplotlib.pyplot as plt
z = np.random.randn(20).reshape((20,1))
X = np.random.randn(20,10)
b = np.array([ele for ele in range(1,11)]) #自己设计
b = b.reshape((10,1))
y = np.dot(X,b) + z
#calculate
fir = np.dot( X.T,X)
fir = np.linalg.inv(fir)
fir = np.dot( fir,X.T)
est_b = np.dot(fir,y)
print( est_b )
print(b)
#draw it
x = np.arange(1,11)
plt.scatter( x , est_b , alpha = 1 , color = 'black', label = 'estimate b' )
plt.scatter( x , b , alpha = 1 , color = 'red' , label = 'true b')
plt.xlabel( 'index' )
plt.ylabel( 'value' )
plt.title( 'blablah' )
plt.legend()
plt.show ()
相应曲线:
三:直方图和密度估计
代码:
import numpy as np import matplotlib.pyplot as plt import scipy.stats
data = np.random.normal( size = 1000 )#the data collected
kernel = scipy.stats.gaussian_kde( data ) #the kde
x = np.linspace( np.min(data) , np.max(data) , 1000 ) # plt.plot( x , kernel.pdf(x) , alpha = 1 ) # draw the pdf plt.hist( data , bins = 25 , density = True )# for histogram
#curve plt.xlabel('x') plt.ylabel('y') plt.title( 'my_function:' ) plt.show()
相应图像:
![](https://i-blog.csdnimg.cn/blog_migrate/1abd95d15579b7f23dd1f3fbd060694e.png)