python - 将 matplotlib imshow 裁剪到值的范围

标签 python numpy matplotlib scipy

我正在尝试以 x、y、z 点的形式根据地球物理学对表面进行插值。我想将表面裁剪到调查的范围(例如,我只想要下图中红色边框内的区域)。

有人知道怎么做吗?下面是生成下图的一些示例代码。我需要弄清楚如何修改它以仅插入红色边框内的区域。

# Import libs
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata

# Create some example data
x = np.array([1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6])
y = np.array([1,2,3,4,2,3,4,5,3,4,5,6,4,5,6,7,5,6,7,8,6,7,8,9])
z = np.linspace(0,100,len(y))

# Grid and interpolate between points
yi, xi = np.mgrid[int(y.min()):int(y.max()),int(x.min()):int(x.max())]
zi = griddata((x, y), z, (xi, yi), method='nearest')

# Plot the figure
plt.imshow(
  zi, extent=[x.min(), x.max(), y.min(), y.max()],
  origin="lower", interpolation='bicubic', aspect='auto'
)
plt.colorbar()
plt.scatter(x,y, c = 'r')
plt.show()

enter image description here

最佳答案

来自docs我的方法是:

# Import libs
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata

from matplotlib.path import Path
from matplotlib.patches import PathPatch

# Create some example data
x = np.array([1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6])
y = np.array([1,2,3,4,2,3,4,5,3,4,5,6,4,5,6,7,5,6,7,8,6,7,8,9])
z = np.linspace(0,100,len(y))

# Grid and interpolate between points
yi, xi = np.mgrid[int(y.min()):int(y.max()),int(x.min()):int(x.max())]
zi = griddata((x, y), z, (xi, yi), method='nearest')

# Plot the figure
im = plt.imshow(
  zi, extent=[x.min(), x.max(), y.min(), y.max()],
  origin="lower", interpolation='bicubic', aspect='auto',
  clip_path=patch, clip_on=True)

plt.colorbar()

path = Path([[1, 1], [1, 4], [6, 9], [6, 6], [1, 1]])
patch = PathPatch(path, facecolor='none')

plt.gca().add_patch(patch)
im.set_clip_path(patch)

enter image description here

为了计算你所在区域的角点,你可以定义一个函数:

def corners(x, y):
    xl = np.min(x)
    yl = np.min(y)
    xh = np.max(x)
    yh = np.max(y)
    return [[xl, yl], [xl, np.max(y[x==xl])], [xh, yh], [xh, np.min(y[x==xh])], [xl, yl]]

并将补丁中的显式点替换为:

...
path = Path(corners(x, y))
...

编辑:

patch = PathPatch(path, facecolor='none', edgecolor='none')

您可以纯粹裁剪,而不必显示裁剪路径的边缘。

enter image description here

关于python - 将 matplotlib imshow 裁剪到值的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52548812/

相关文章:

Python 相当于 Scala groupby

python - 交错两个 numpy 索引数组,每个数组中的一项

python - 使用 RGB 元组的 Matplotlib pcolormesh

python - 使用 nx. Degree_histogram 绘制图的度分布

python - 将向量存储在 numpy 矩阵的单元格中

python - plt.show() 在spyder ide 中不起作用

Python - 字符串搜索

python - Pyspark:按键聚合 RDD,然后也按键对元组值列表求和

python - 在tensorflow代码中使用keras层

python - 如果其他单元格包含 'something',如何在 2 个单元格中设置值