排列数据以制作3d曲面图

时间:2017-03-29 22:56:23

标签: python matplotlib mplot3d

我正在尝试制作3D曲面图,但我无法将数据转换为正确的格式。

重塑我的Z变量给了我:' ValueError:新数组的总大小必须保持不变'。 Z的形状是(2500,50)。 X和Y的形状都是(50,50)。我不确定为什么会这样。我的代码中是否存在我错过的明显错误?

import numpy as np 
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt


def Mountain(F, P):
    TA = ((TAmax-TAmin) * (((FF**g)/((FF**g)+FFhm**g)**a)/((((FF**g)/((FF**g)+FFhm**g))**a)+(SP/SPe)**a)))
    return TA


F = np.linspace(0,120)
P = np.linspace(0,100)
Fb= int(21)
Fro= int(362)
FFhm = int(63)
g= int(3)
a = int(3)
SPmin = float(1.82)
SPbend = float(0.5)
SPe = int(10)
TAmax= int(1)
TAmin = int(0)

SP = SPmin + SPbend * np.log(1 + np.exp((P - SPmin)/SPbend))

FF= (Fb * (np.log(1 + np.exp(Fro/Fb)) - np.log(1 + np.exp((Fro-F)/Fb))))


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y = np.meshgrid(F, P)
gh= list(zip(np.ravel(X), np.ravel(Y)))
zs = np.array(Mountain(F,P) for F,P in gh)
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('F')
ax.set_ylabel('P')
ax.set_zlabel('TA')

plt.show()

2 个答案:

答案 0 :(得分:2)

请注意,zs为空。如果你想做列表理解,你应该使用括号(所以np.array([Mountain(F,P) for F,P in gh])),虽然你真正想要的是zs = np.array([Mountain(X[i],Y[i]) for i in range(X.shape[0])])而不是ravel。

plot output

答案 1 :(得分:1)

你必须为每对(X,Y)加上z值。这意味着您不需要numpy.ravel。 X,Y和Z的大小必须相同:

import numpy as np 
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt


def Mountain(F, P):
    TA = ((TAmax-TAmin) * (((FF**g)/((FF**g)+FFhm**g)**a)/((((FF**g)/((FF**g)+FFhm**g))**a)+(SP/SPe)**a)))
    return TA


F = np.linspace(0,120)
P = np.linspace(0,100)
Fb= int(21)
Fro= int(362)
FFhm = int(63)
g= int(3)
a = int(3)
SPmin = float(1.82)
SPbend = float(0.5)
SPe = int(10)
TAmax= int(1)
TAmin = int(0)

SP = SPmin + SPbend * np.log(1 + np.exp((P - SPmin)/SPbend))
FF= (Fb * (np.log(1 + np.exp(Fro/Fb)) - np.log(1 + np.exp((Fro-F)/Fb))))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y = np.meshgrid(F, P)
Z = np.array(Mountain(F,P))

ax.plot_surface(X, Y, Z)

ax.set_xlabel('F')
ax.set_ylabel('P')
ax.set_zlabel('TA')

plt.show()

enter image description here