Litwos
Litwos

Reputation: 1348

2D array to 3D area function - Python

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

Upvotes: 0

Views: 1305

Answers (1)

LRP
LRP

Reputation: 118

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)

Upvotes: 1

Related Questions