我在準備用于 pcolormesh 圖中的陣列時遇到問題。目前,我正在對 x 和 y 陣列的組合實施決策函式以生成 z,這是一種等值面值(在某種程度上)。代碼如下,
def region(nx, ny):
if nx >= 0 and ny >= 0:
r = 1
elif nx < 0 and ny >= 0:
r = 2
elif nx < 0 and ny < 0:
r = 3
elif nx >= 0 and ny < 0:
r = 4
return r
x = np.linspace(-10, 10, 41)
y = np.linspace(-20, 20, 41)
z = np.array([region(i, j) for j in y for i in x])
X, Y = np.meshgrid(x, y)
Z = z.reshape(41, 41)
discrete_colors = [sns.color_palette("Paired")[0],
sns.color_palette("Paired")[2],
sns.color_palette("Paired")[6],
sns.color_palette("Paired")[8]]
my_colormap = colors.ListedColormap(discrete_colors)
fig, ax = plt.subplots()
cmap = plt.get_cmap('RdBu', 4)
# c = ax.pcolormesh(X, Y, Z,cmap=cmap, vmin = np.min(Z)-.5, vmax = np.max(Z) .5)
c = ax.pcolormesh(X, Y, Z,cmap=my_colormap, vmin = np.min(Z)-.5, vmax = np.max(Z) .5)
cbar = fig.colorbar(c, ax=ax, ticks=np.arange(np.min(Z),np.max(Z) 1))
cbar.set_ticklabels(['Region 1','Region 2','Region 3','Region 4'])
ax.set_xlim(min(x)-0.5, max(x) 0.5)
ax.set_ylim(min(y)-0.5, max(y) 0.5)
plt.show()
有沒有更好的方法從 x 和 y 創建 z 陣列?也許編輯決策功能?我正在使用一個非常大的資料集,因此當前的實作速度相當慢。
uj5u.com熱心網友回復:
您可以只使用布爾索引:
Z = np.zeros_like(X)
Z[(X>=0) & (Y>=0)] = 1
Z[(X<0) & (Y>=0)] = 2
Z[(X<0) & (Y<0)] = 3
Z[(X>=0) & (Y<0)] = 4
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/361995.html
下一篇:numpy標量乘法如何作業?
