0

I am trying to write a function that creates a 3D surface of a 2D input numpy array, having the number of rows and columns as X and X, and the values in the array as the Z values. I searched on SO for examples of 3D plots, and adapted this example (Plotting a 2d Array with mplot3d) into the function below:

def area_plot(a):
    rows = range(a.shape[0])
    columns = range(a.shape[1])
    hf = plt.figure()
    ha = hf.add_subplot(111, projection= "3d")
    X, Y = np.mgrid(rows, columns)
    ha.plot_surface(X,Y, arr)
    plt.show()

The example array is this:

arr = np.array([(1,1,1,2,2,3,2,2,1,1,1),
                (1,1,1,2,3,3,3,2,1,1,1),
                (1,1,1,2,3,10,3,2,1,1,1),
                (1,1,1,2,3,3,3,2,1,1,1),
                (1,1,1,2,2,3,2,2,1,1,1)])

area_plot(arr)

But I get this error, and I don't know how to fix it. Thanks!

TypeError: 'nd_grid' object is not callable

0

1 Answer 1

1

Looks like you weren't using np.mgrid correctly. See below:

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


def area_plot(a):
    rows = range(a.shape[0])
    columns = range(a.shape[1])
    hf = plt.figure()
    ha = hf.add_subplot(111, projection= "3d")
    X, Y = np.mgrid[0: len(rows), 0:len(columns)]
    ha.plot_surface(X,Y, a)
    plt.show()

arr = np.array([(1,1,1,2,2,3,2,2,1,1,1),
                (1,1,1,2,3,3,3,2,1,1,1),
                (1,1,1,2,3,10,3,2,1,1,1),
                (1,1,1,2,3,3,3,2,1,1,1),
                (1,1,1,2,2,3,2,2,1,1,1)])

area_plot(arr)
Sign up to request clarification or add additional context in comments.

3 Comments

This code yields a ValueError: total size of new array must be unchanged
I get this error message: 'ValueError: shape mismatch: two or more arrays have incompatible dimensions on axis 0.'
@LPR That fixes the ValueError and is most likely what the OP is looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.