Section of the plot by heat map

I have an array of form (201,201), I would like to build several sections according to the data, but I had problems accessing the corresponding points. For example, let's say I want to build a section defined by a line in a drawing created

from pylab import * Z = randn(201,201) x = linspace(-1,1,201) X,Y = meshgrid(x,x) pcolormesh(X,Y,Z) plot(x,x*.5) 

I would like to build them in different directions, but they will always go through the source if that helps ...

+4
source share
1 answer

Basically, you want to interpolate a 2D mesh along a line (or an arbitrary path).

First of all, you must decide whether you want to interpolate the grid or just select the nearest neighbors. If you want to do the latter, you can simply use indexing.

If you want to interpolate, look at scipy.ndimage.map_coordinates . At first it’s a little difficult for you to wrap your head, but it is perfect for this. (This is much more efficient than using an interpolation procedure, assuming data points are distributed randomly.)

I will give an example of both. They are adapted from the answer that I gave to another question. However, in these examples, everything is built in pixel coordinates (ie, row, column).

In your case, you are working in a different coordinate system than the coordinates of the "pixel", so you will need to convert from the coordinates of the "world" (ie x, y) to the "pixel" coordinates for interpolation.

Firstly, here is an example of using cubic interpolation with map_coordinates :

 import numpy as np import scipy.ndimage import matplotlib.pyplot as plt # Generate some data... x, y = np.mgrid[-5:5:0.1, -5:5:0.1] z = np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2) # Coordinates of the line we'd like to sample along line = [(-3, -1), (4, 3)] # Convert the line to pixel/index coordinates x_world, y_world = np.array(zip(*line)) col = z.shape[1] * (x_world - x.min()) / x.ptp() row = z.shape[0] * (y_world - y.min()) / y.ptp() # Interpolate the line at "num" points... num = 1000 row, col = [np.linspace(item[0], item[1], num) for item in [row, col]] # Extract the values along the line, using cubic interpolation zi = scipy.ndimage.map_coordinates(z, np.vstack((row, col))) # Plot... fig, axes = plt.subplots(nrows=2) axes[0].pcolormesh(x, y, z) axes[0].plot(x_world, y_world, 'ro-') axes[0].axis('image') axes[1].plot(zi) plt.show() 

enter image description here

Alternatively, we can use interpolation of the nearest neighbor. One way to do this is to pass order=0 to map_coordinates in the example above. Instead, I will use indexing to show a different approach. If we just change the line

 # Extract the values along the line, using cubic interpolation zi = scipy.ndimage.map_coordinates(z, np.vstack((row, col))) 

To:

 # Extract the values along the line, using nearest-neighbor interpolation zi = z[row.astype(int), col.astype(int)] 

We'll get:

enter image description here

+5
source

All Articles