【问题标题】:Plot cross section through heat map通过热图绘制横截面
【发布时间】:2013-09-26 01:38:59
【问题描述】:

我有一个形状数组(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)

我想以不同的方向绘制它们,但如果有帮助,它们将始终通过原点...

【问题讨论】:

  • 你能写出包含所有导入的代码吗?

标签: python numpy matplotlib


【解决方案1】:

基本上,您希望沿一条线(或任意路径)插入一个 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()

或者,我们可以使用最近邻插值。一种方法是在上面的示例中将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)]

我们会得到:

【讨论】:

  • 感谢三次插值示例正是我所需要的。
  • 变化不大:x_world, y_world = np.array((zip(*line)) => x_world, y_world = np.array(list(zip(*line))))
  • 我们可以检索采样线距离作为第二个绘图的 x 轴吗?而不是 200,400 ... 1000,我想显示从 point1 到 point2 的总距离。
猜你喜欢
  • 2018-08-19
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多