欢迎前往我的个人博客阅读原文。
Python的Matplotlib库是一个比较强大的绘图库,可以比较好的代替Matlab实现绘图功能。下面我从学校开设的Matlab上机实验课程中的练习题挑出与绘图相关的练习给出Python代码,仅供参考。
Matplotlib库通常用来绘制二维曲面图形,下面我们给出了二维曲线的一个标记的例子和一个绘制子图的例子;其余的例子都是绘制三维图形,这需要将坐标轴设置为三维的坐标系,我们主要采用下列方式进行设置:
fig = plt.figure()
ax = fig.subplot(111, projection='3d')
另外一种方式需要调用Matplotlib库的一个工具包,可以自行网上搜索进行学习。
可以前往我的GitHub查看源代码。
示例一 曲线的标记
绘出函数 y = 3 cos x e sin x y=3\cos x e^{\sin x} y=3cosxesinx 在 [ 0 , 5 ] [0,5] [0,5] 上黑色实型曲线图,线宽为3,数据点用圆圈标记的,尺寸为6,标记点的边缘颜色为红色,标记点的填充颜色为绿色;加栅阁并且绘图区域为正方形,各坐标轴采用登场刻度。
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__':
x = np.arange(0, 5, 0.1)
y = 3*np.cos(x)*np.exp(np.sin(x))
fig, ax = plt.subplots()
ax.plot(x, y, 'k-o', linewidth=3,
markeredgecolor='r',
markerfacecolor='g',
markersize=10)
ax.grid(True)
plt.axis('equal')
plt.show()
绘制的图形如下图所示:
示例二 参数方程
绘制曲线 { x = 2 ( cos t + t sin t ) y = 2 ( sin t − t cos t ) z = 1.5 t \begin{cases} x = 2(\cos t + t\sin t) \\ y = 2(\sin t - t\cos t) \\ z=1.5t \end{cases} ⎩⎪⎨⎪⎧x=2(cost+tsint)y=2(sint−tcost)z=1.5t, t t t 的变化范围为 [ 0 , 10 π ] [0, 10\pi] [0,10π].
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__':
t = np.arange(0, 10*np.pi, 0.1*np.pi)
x = 2*(np.cos(t) + t*np.sin(t))
y = 3*(np.sin(t) - t*np.cos(t))
z = 1.5*t
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot3D(x, y, z)
plt.show()
plot3D()
是用来绘制三维曲线的,类似于plot()
函数。绘制的图形如下图所示:
绘制环面图形,其参数方程为:
{ x = ( 2 + cos u ) cos v y = ( 2 + cos u ) sin v z = sin u u ∈ [ 0 , 2 π ] , v ∈ [ 0 , 2 π ] \begin{cases} x = (2 + \cos u)\cos v \\ y = (2 + \cos u)\sin v \\ z = \sin u \end{cases} \quad\quad\quad u\in[0,2\pi],v\in[0,2\pi] ⎩⎪⎨⎪⎧x=(2+cosu)cosvy=