1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
import os import matplotlib.pyplot as plt import numpy as np from scipy import interpolate os.chdir(r'D:\data\scripts\web1\ex29') os.getcwd() np.random.seed(115925231) x = y = np.linspace(-1, 1, 100) X, Y = np.meshgrid(x, y) def f(x, y): return np.exp(-x**2 - y**2) * np.cos(4*x) * np.sin(6*y) Z = f(X, Y) N = 500 xdata = np.random.uniform(-1, 1, N) ydata = np.random.uniform(-1, 1, N) zdata = f(xdata, ydata) fig, ax = plt.subplots(figsize=(8, 6)) c = ax.contourf(X, Y, Z, 15, cmap=plt.cm.bwr); ax.scatter(xdata, ydata, marker='.') ax.set_ylim(-1,1) ax.set_xlim(-1,1) ax.set_xlabel(r"$x$", fontsize=20) ax.set_ylabel(r"$y$", fontsize=20) cb = fig.colorbar(c, ax=ax) cb.set_label(r"$z$", fontsize=20) fig.tight_layout() plt.savefig("example29.png", dpi=100) plt.show() plt.close() def z_interpolate(xdata, ydata, zdata): Zi_0 = interpolate.griddata((xdata, ydata), zdata, (X, Y), method='nearest') Zi_1 = interpolate.griddata((xdata, ydata), zdata, (X, Y), method='linear') Zi_3 = interpolate.griddata((xdata, ydata), zdata, (X, Y), method='cubic') return Zi_0, Zi_1, Zi_3 fig, axes = plt.subplots(3, 3, figsize=(12, 12), sharex=True, sharey=True) n_vec = [50, 150, 1000] for idx, n in enumerate(n_vec): Zi_0, Zi_1, Zi_3 = z_interpolate(xdata[:n], ydata[:n], zdata[:n]) axes[idx, 0].contourf(X, Y, Zi_0, 15, cmap=plt.cm.bwr) axes[idx, 0].set_ylabel("%d data points\ny" % n, fontsize=12) axes[idx, 0].set_title("nearest", fontsize=12) axes[idx, 1].contourf(X, Y, Zi_1, 15, cmap=plt.cm.bwr) axes[idx, 1].set_title("linear", fontsize=12) axes[idx, 2].contourf(X, Y, Zi_3, 15, cmap=plt.cm.bwr) axes[idx, 2].set_title("cubic", fontsize=12) for m in range(len(n_vec)): axes[idx, m].set_xlabel("x", fontsize=12) fig.tight_layout() plt.savefig("example29_1.png", dpi=100) plt.show() plt.close() <img class=" wp-image-140 aligncenter" src="https://gantovnik.com/bio-tips/wp-content/uploads/2019/01/example29.png" alt="example29" width="597" height="448" /> <img class=" wp-image-141 aligncenter" src="https://gantovnik.com/bio-tips/wp-content/uploads/2019/01/example29_1.png" alt="example29_1" width="614" height="614" /> |
Recent Comments