[英]Wrong orientation of a contour plot in Python using Matplotlib's contourf()
我是 Python 的初學者,我將嘗試根據 x 和 y 可視化 function。 使用輪廓 plot 應該更容易看到最大值。
那是我的代碼和output。問題在下面。
# Generate synthetic plot
x_fine=np.linspace(-4,10,100).reshape(-1,1)
y_fine=np.linspace(-3,3,100)
f_xy=1.5*np.sin(x_fine) - 0.1*(x_fine-3)**2 +10 - 0.5*(y_fine**2-2) + np.sin(y_fine)*2
#f_xy= -(x_fine-2)**2 - (y_fine)**2 +20
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(x_fine, y_fine, f_xy, cmap=cm.coolwarm, linewidth=0, antialiased=False, alpha=0.6)
ax.contourf(x_fine.flatten(),y_fine, f_xy, zdir='z', offset=-0, cmap=cm.coolwarm,alpha=0.7)
ax.set_xlabel("$x$")
ax.set_ylabel("$y$")
ax.set_zlabel("Objective")
plt.show()
所以,如果你可能會看到,plot 輪廓 plot 顯示輪廓,但不知何故旋轉了 90 度。 如果我只是更改輪廓 plot 方法中的 x 和 y 輸入,圖形就會變形。 如果我在輪廓 plot 和 plot_surface 命令中更改 x 和 y 輸入,則圖形會正確顯示。 但是,我需要將我的 x 軸聲明為“y”,反之亦然,我想避免這種情況。
我希望我把我的問題說清楚了。 我有興趣閱讀您的回答,我可能做錯了什么或代碼的行為為何如此:D
在 numpy 中,坐標軸按行列排列,例如
a = np.zeros((3, 2))
a
>>> [[0, 0],
[0, 0],
[0, 0]]
當您將x_fine
重塑為(-1, 1)
時,您將其寬度設置為 1,高度設置為 N。類似的東西。
x_fine
>> [[-4],
[-3.96],
...
[10]]
按照 x 橫向和 y 向上/向下的約定,這是錯誤的方向。
將reshap(-1, 1)
放在y_fine
上。 然后,當您在y_fine
而不是x_fine
上繪制輪廓調用flatten()
時。
現在這兩個地塊的方向相同。 如果您想驗證它們是否正確旋轉,而不是同時旋轉 90 度,請將 f_xy 設置為簡單的值,例如f_xy = x_fine + np.zeros_like(y_fine)
,您會看到它們都在x
方向上增加。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.