我有一个脚本,它创建一个带有XYZ值的dict。下面的判据包括x处的值,从-2到2,y从0到2。
my_dict = {
-2:{0:1,1:1,2:0},
-1:{0:3,1:1,2:0},
0:{0:6,1:1,2:9},
1:{0:-2,1:1,2:2},
2:{0:1,1:1,2:6}}现在,我不知道如何在此基础上创建3D图。我知道matplotlib库,但我不确定如何生成Z-Data。我试着写一个函数,让我的Z数据在网格中,但它不起作用。这就是我到目前为止得到的:
x = np.arange(-2, 2, 1)
y = np.arange(0, 2, 1)
X, Y = np.meshgrid(x, y)
Z = f(X,Y) #HERE, the function f is what I am searching for.
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50, cmap='binary')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')有没有任何麻木或蟒蛇的方法来做到这一点?
发布于 2021-09-20 07:39:47
这就是你要找的吗?
my_dict = {
-2:{0:1,1:1,2:0},
-1:{0:3,1:1,2:0},
0:{0:6,1:1,2:9},
1:{0:-2,1:1,2:2},
2:{0:1,1:1,2:6}}
x = np.arange(-2, 3, 1)
y = np.arange(0, 3, 1)
X, Y = np.meshgrid(x, y)
def f(x, y):
z = np.zeros(X.reshape(-1).shape) # Create an "empty" tensor that matches the "flattened" meshgrid
c = 0 # To index over our "z"
for i in y:
for j in x:
z[c] = my_dict[j][i] # Fill the empty tensor with its corresponding values from the dictionary (depending on x and y)
c += 1
z = z.reshape(X.shape) # Reshape it back to match meshgrid's shape
return z
Z = f(x, y)
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50, cmap='binary')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()发布于 2021-09-20 07:25:31
我相信你可以通过以下方式访问你的字典中的正确值:
Z = mydict[x][y]
https://stackoverflow.com/questions/69250123
复制相似问题