通过热图绘制横截面

时间:2013-09-20 15:35:17

标签: python numpy matplotlib

我有一个形状数组(201,201),我想在数据中绘制一些横截面,但我无法访问相关点。例如,我想绘制由图中的线给出的横截面,

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)

我想在不同的方向上绘制这些图,但如果有帮助的话,它们将始终通过原点......

1 个答案:

答案 0 :(得分:5)

基本上,您希望沿线(或任意路径)插入2D网格。

首先,您应该决定是要插入网格还是仅进行最近邻采样。如果你想做后者,你可以使用索引。

如果您想进行插值,请查看scipy.ndimage.map_coordinates。起初有点难以绕开,但这对于它来说是完美的。 (它比使用假定数据点随机分布的插值例程更有效率。)

我将举两个例子。这些改编自answer I gave to another question.但是,在这些例子中,所有内容都以“像素”(即行,列)坐标绘制。

在您的情况下,您使用的是与“像素”坐标不同的坐标系,因此您需要将“世界”(即x,y)坐标转换为插值的“像素”坐标。

首先,这是一个使用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

或者,我们可以使用最近邻插值。一种方法是在上面的示例中将order=0传递给map_coordinates。相反,我将使用索引来展示另一种方法。如果我们只是更改行

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

要:

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

我们会得到:

enter image description here