用pylab绘制微分方程组解的轮廓图
我正在用数值方法解决一组微分方程,得到了 x、y 和 z 的解。每个数组都是一维的,比如 x[0]、y[0]、z[0] 代表空间中的一个点。我想把这些点画成一个等高线图,就像平常的 x、y、z 坐标那样。可是我发现 z 需要是一个二维数组,我知道怎么从 x 和 y 创建一个网格,但我不知道该怎么处理 z。
如果有人能给我一些建议,我会非常感激。
2 个回答
1
仅仅把x和y的数据放在一起是不够的,你还需要把数据整理成一个规则的网格,这样才能做出等高线图。为了做到这一点,你可以看看 matplotlib.mlab.griddata
这个工具(http://matplotlib.org/examples/pylab_examples/griddata_demo.html)。
我会把下面链接中的示例代码粘贴过来,并加上一些额外的注释:
from numpy.random import uniform, seed
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
import numpy as np
# Here the code generates some x and y coordinates and some corresponding z values.
seed(0)
npts = 200
x = uniform(-2,2,npts)
y = uniform(-2,2,npts)
z = x*np.exp(-x**2-y**2)
# Here you define a grid (of arbitrary dimensions, but equal spacing) onto which your data will be mapped
xi = np.linspace(-2.1,2.1,100)
yi = np.linspace(-2.1,2.1,200)
# Map the data to the grid to get a 2D array of remapped z values
zi = griddata(x,y,z,xi,yi,interp='linear')
# contour the gridded data, plotting dots at the nonuniform data points.
CS = plt.contour(xi,yi,zi,15,linewidths=0.5,colors='k')
CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.rainbow,
vmax=abs(zi).max(), vmin=-abs(zi).max())
plt.colorbar() # draw colorbar
# Plot the original sampling
plt.scatter(x,y,marker='o',c='b',s=5,zorder=10)
plt.xlim(-2,2)
plt.ylim(-2,2)
plt.title('griddata test (%d points)' % npts)
plt.show()