如何将特定范围外的点设置为0

How can I set the points outside of the certain range to 0

我插值了一个图并扩展了 x 和 y,这给了我以下等高线图。如何重新排列Z矩阵,使红框外的点为0.

x=data.columns.astype('float64')
y=data.index.to_numpy()
z=data.to_numpy() 
X,Y = np.meshgrid(x, y)

ratio = 4
x_new = x*ratio
y_new=y*ratio
#plt.plot(x_new,y_new)

f = interpolate.interp2d(x, y, z, kind='linear')
z_new = f(x_new, y_new)
X_new,Y_new = np.meshgrid(x_new, y_new)

plt.contourf(X_new, Y_new, znew, alpha = 1, cmap=plt.cm.inferno)

这是一个最小的例子,应该很容易适应你的情况。 np.where 函数是你的朋友:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-15, 15, 301)
y = np.linspace(-15, 5, 201)

X_new, Y_new = np.meshgrid(x, y)

znew = np.random.randn(*X_new.shape)

znew = np.where((X_new > 5) & (X_new < 10) & 
                (Y_new > -2) & (Y_new < 2), znew, 0)

plt.contourf(X_new, Y_new, znew, alpha = 1, cmap=plt.cm.inferno)