Python 3D Plot from dictonary values

Viewed 89

I do have a script, which creates a dict with XYZ-values. Following dict includes values at x from -2 to 2, with y from 0 to 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}}

Now, I don't now how to create a 3D plot out of this. I am aware of the matplotlib library,but I am not sure how to generate my Z-Data. I tried to write a function, to get my Z-data in a mesh, but it doesn't work. This is what I got so far:

    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')

Is there any numpy or pythonic way to do this?

2 Answers

Is this what you're looking for?

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()

I believe you can get away with accessing the correct value in your dict via:

Z = mydict[x][y]

Related