我需要在给定一些非结构化(x, y)
坐标的情况下生成二维密度图,并使用一个z
值作为分配给每个点的权重。
我可以使用scipy.interpolate.Rbf或scipy.interpolate.griddata将值插入网格(请参阅下面的代码)。第一个非常准确,但非常慢,而第二个很多更快但明显不太准确。
请参阅下面的图片,其中Rfb
位于左侧,griddata
位于右侧:
有没有办法在这两个功能之间妥协?什么会产生一个与Rfb
函数更相似但速度更接近griddata
函数的结果?
# Data
N = 1000
x, y, z = np.random.uniform(0.0005, 0.03, N),\
np.random.uniform(6., 10., N), np.random.uniform(1., 10., N)
xmin, xmax, ymin, ymax = min(x), max(x), min(y), max(y)
# Set up a regular grid of interpolation points
xi, yi = np.linspace(xmin, xmax, 200), np.linspace(ymin, ymax, 200)
xi, yi = np.meshgrid(xi, yi)
# Normalize data and grid.
x_new, xi_new = (x - xmin) / (xmax - xmin), (xi - xmin) / (xmax - xmin)
y_new, yi_new = (y - ymin) / (ymax - ymin), (yi - ymin) / (ymax - ymin)
# Interpolate new data with Rbf.
s = time.clock()
rbf = scipy.interpolate.Rbf(x_new, y_new, z, function='linear')
zi = rbf(xi_new, yi_new)
print(time.clock() - s)
# Plot density map.
ax1 = plt.subplot(121)
plt.pcolormesh(xi, yi, zi, cmap=plt.get_cmap('GnBu_r'), zorder=2)
plt.contour(xi, yi, zi, 2, colors='#551a8b', linewidths=0.5, zorder=3)
# Interpolate new data with griddata.
s = time.clock()
# Python 2.7
vals = zip(*[x_new, y_new])
# Python 3.6
# vals = np.array([x_new, y_new]).T
zi = scipy.interpolate.griddata(vals, z, (xi_new, yi_new), method='linear')
print(time.clock() - s)
# Plot density map.
ax2 = plt.subplot(122)
plt.imshow(
zi, extent=(xmin, xmax, ymin, ymax), origin='lower',
cmap=plt.get_cmap('GnBu_r'))
plt.contour(xi, yi, zi, 2, colors='#551a8b', linewidths=0.5, zorder=3)
plt.show()