3

Lets say I have data as follows:

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

where I have a set of coordinates and an associated value between 0 and 100. Lets say the coordinates represent houses in a suburb.

How do I interpolate this data so as to create a meshgrid to use when plotting.

Baz
  • 12,713
  • 38
  • 145
  • 268
  • @importanceofbeingernest I am not sure I'd call that a duplicate. The data are in a different format, and `matplotlib.mlab.griddata()` is not the best solution, IMO. – Matt Hall Feb 04 '18 at 13:46
  • @kwinkunks The data format is essentially the same, namely some points in 3D space. There are several solution shown, e.g. `matplotlib.mlab.griddata` or `scipy.interpolate.griddata`. The idea is that such solutions are bundled in at a single point. So if you have a better solution to this question, please provide it as answer to the duplicate, such that everyone may benefit from it. – ImportanceOfBeingErnest Feb 04 '18 at 21:49

2 Answers2

1

Here's a way to use SciPy's radial basis function interpolator. Omit the %matplotlib inline magic if you're not in a notebook.

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

Matt Hall
  • 7,614
  • 1
  • 23
  • 36
1

You only need to interpolate if you're going to plot a contour. In that case, you might need to think about what the appropriate interpolation is, although kwinkunks has a great first pass go.

To skip the interpolation, just plot a 3D scatter plot:

# 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

Heath Raftery
  • 3,643
  • 17
  • 34