插值基于坐标的数据以生成网格网格

时间:2018-02-04 01:05:58

标签: python python-3.x numpy matplotlib

假设我的数据如下:

data = {(1,3):22, (1,3.5):23, (1,4.5):25, ..., (1.5,3.3): 19, ... (4,4):100 }

我有一组坐标和0到100之间的相关值。让我们说坐标代表郊区的房屋。

如何插入此数据以创建在绘图时使用的meshgrid

2 个答案:

答案 0 :(得分:1)

这是一种使用SciPy的径向基函数插值器的方法。如果你不在笔记本中,请忽略%matplotlib inline魔法。

import numpy as np
from scipy.interpolate import Rbf
%matplotlib inline
import matplotlib.pyplot as plt

data = {(1,3):22, (1,3.5):23, (1,4.5):25, (1.5,3.3):19, (4,4):100}

# Extract the data.
x = np.array([k[0] for k in data.keys()])
y = np.array([k[1] for k in data.keys()])
z = np.array([v for v in data.values()])

# Make the grid.
minx, maxx = np.amin(x), np.amax(x)
miny, maxy = np.amin(y), np.amax(y)
extent = (minx, maxx, miny, maxy)
grid_x, grid_y = np.mgrid[minx:maxx:0.01, miny:maxy:0.01]

# Make an n-dimensional interpolator.
rbfi = Rbf(x, y, z)

# Predict on the regular grid.
z_ = rbfi(grid_x, grid_y)

# Look at it!
plt.imshow(z_, origin="lower", extent=extent)
plt.scatter(x, y, s=2, c='w')

Result of script

答案 1 :(得分:1)

如果您要绘制轮廓,则只需插值。在这种情况下,你可能需要考虑适当的插值是什么,虽然kwinkunks有一个很好的第一遍。

要跳过插值,只需绘制三维散点图:

# Just plotting libraries, no numpy
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d

# Using your data as an example
data = {(1,3):22, (1,3.5):23, (1,4.5):25, (1.5,3.3): 19, (4,4):100 }

# Extract the x, y and z coordinates
x = [coord[0] for coord in list(data)]
y = [coord[1] for coord in list(data)]
z = list(data.values())

# Ready the plot environment for 3D plots
ax = plt.axes(projection='3d')

# Plot a scatter plot (coloured by z value just for example)
ax.scatter(x,y,z,c=z)

# Show result
plt.show()

enter image description here