Liu Chong Liu Chong - 15 days ago 5
Python Question

When I use mplot3D, why get error: NameError: name 'plot_trisurf' is not defined

I try to use mplot3D to draw some 3D pictures:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
...
plot_trisurf(X, Y, Z1)


Then my computer will tell me that

NameError: name 'plot_trisurf' is not defined


Why this happen? I thought I have imported it already.

Answer

plot_trisurf is a method from the Axes3D class. In python, in order to call a class method, you usually need to provide the class or an instance of it.

In this case the class instance would be your axes object. This is usually called ax. The correct call would therefore be (as seen on the matplotlib trisurf example):

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.gca(projection='3d')
...
ax.plot_trisurf(x, y, z)
plt.show()
Comments