Below is my code (from here): So "/>
  简体   繁体   中英

Finding x and y values corresponding to given z value in 3D numpy object

I have a numpy object in Python ( np ) with which I am plotting a graph in pyplot . It is a 3D graph with x , y and z being lists containing the values for which the graph is to be plotted. 我正在获取<code> pyplot </ code>图表 Below is my code (from here ):

data = np.c_[x,y,z]

# regular grid covering the domain of the data
mn = np.min(data, axis=0) - 0.009
mx = np.max(data, axis=0) + 0.009

X,Y = np.meshgrid(np.linspace(mn[0], mx[0]), np.linspace(mn[1], mx[1]))
XX = X.flatten()
YY = Y.flatten()
A = np.c_[np.ones(data.shape[0]), data[:, :2], np.prod(data[:, :2], axis=1), data[:, :2] ** 2]
C, _, _, _ = scipy.linalg.lstsq(A, data[:, 2])

# evaluate it on a grid
Z = np.dot(np.c_[np.ones(XX.shape), XX, YY, XX * YY, XX ** 2, YY ** 2], C).reshape(X.shape)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, alpha=0.2)
ax.scatter(data[:, 0], data[:, 1], data[:, 2], c='r', s=50)
plt.xlabel('X')
plt.ylabel('Y')
ax.set_zlabel('Z')
ax.axis('equal')
ax.axis('tight')
plt.show()

So here, I want to get the values of x and y , where the value of z is closest to -30 . How do I get those values of x and y .

You can try following (see also Find nearest value in numpy array )

value = 30.
zid = (np.abs(Z-value)).argmin()
xval = np.reshape(X, -1)[zid]
yval = np.reshape(Y, -1)[zid]
print xval, yval, np.reshape(Z, -1)[zid]

I've checked it on the example ( https://gist.github.com/amroamroamro/1db8d69b4b65e8bc66a6 ) you referred in the question and it seems to work.

You can use np.where to get the indices which satisfy the condition -30-eps < z < -30+eps for some tolerance, eps , and use these to get the value of x and y , eg

eps = 10.
ind = np.where((-30+eps > Z.ravel()) & (Z.ravel() > -30-eps))

print("x=",X.ravel()[ind],"y=",Y.ravel()[ind])

I'm a bit unsure exactly how to do this in your case as your plot differs from the example values from the link (please make code in question a MCVE ). The idea should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM