今天第一次使用python的Matplotlib库,绘制函数非常方便,参考Matplotlib官方指南绘制了正余弦函数和抛物线.通过下面的代码可以快速实现Matplotlib入门
安装
pip install matplotlib
绘制正余弦函数
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)
plt.plot(X,C)
plt.plot(X,S)
plt.show()
把上面代码加到plot01.py文件中,运行
python plot01.py
效果:
可以np.linspace()函数可以对数据进行等分,返回numpy数组.np.linspace(-np.pi, np.pi, 256,endpoint=True)把-pi到pi直接的数均分为256份,并存储到X中.打印X查看:
print(X)
结果
[
-3.14159265 -3.11695271 -3.09231277 -3.06767283 -3.04303288 -3.01839294
-2.993753 -2.96911306 -2.94447311 -2.91983317 -2.89519323 -2.87055329
-2.84591335 -2.8212734 -2.79663346 -2.77199352 -2.74735358 -2.72271363
-2.69807369 -2.67343375 -2.64879381 -2.62415386 -2.59951392 -2.57487398
-2.55023404 -2.52559409 -2.50095415 -2.47631421 -2.45167427 -2.42703432
-2.40239438 -2.37775444 -2.3531145 -2.32847456 -2.30383461 -2.27919467
-2.25455473 -2.22991479 -2.20527484 -2.1806349 -2.15599496 -2.13135502
-2.10671507 -2.08207513 -2.05743519 -2.03279525 -2.0081553 -1.98351536
-1.95887542 -1.93423548 -1.90959553 -1.88495559 -1.86031565 -1.83567571....3.11695271 3.14159265]
绘制抛物线:
X1=np.linspace(-4,4,100,endpoint=True)
plt.plot(X1,(X1**2)/9)