Reputation: 4329
I have a data set of discrete, sparse points (x, y, value). I'd like to plot the data so that every (x, y) coordinate is given a color based on interpolation between nearby data points.
data = np.array([
[0, 0, 18.75],
[0, 2, 0],
[0, 4, 16],
[0, 6, 2],
[-4, 2, 18],
[-4, 4, 35],
[-4, 6, 32],
[-4, 8, 15],
[-4, 10, 28],
[4, 0, 26],
[4, 2, 30],
[4, 4, 32],
[4, 6, 35],
[4, 8, 26.5],
])
I've tried using pcolormesh
but it expects my C
values are a 2D array. How can I achieve this?
Upvotes: 1
Views: 1263
Reputation: 4329
I adapted an example of scipy.interpolate.griddata
, with plt.contourf()
as suggested by Matt Pitkin:
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import griddata
x, y, vals = data[:,0], data[:,1], data[:,2]
X, Y = np.meshgrid(
np.linspace(np.min(x), np.max(x), 100),
np.linspace(np.min(y), np.max(y), 100)
)
interpolated_vals = griddata((x, y), vals, (X, Y), method='cubic')
plt.contourf(X, Y, interpolated_vals)
plt.show()
Upvotes: 2
Reputation: 6407
You could try using contourf
and doing the following:
from matplotlib import pyplot as plt
# create mesh grid for x/y-data
grid = np.meshgrid(data[:,0], data[:,1])
# create 2D array of z-values
vals = np.zeros((len(data), len(data)))
for row in data:
vals[(grid[0] == row[0]) & (grid[1] == row[1])] = row[2]
# create contour plot
plt.contourf(data[:, 0], data[:, 1], vals)
Upvotes: 1