Nate Stemen
Nate Stemen

Reputation: 1311

Using matplotlib to make 3D plot

Just trying to make a 3D plot of a constant (0). So I have

width = 1
dx = 0.1
X = np.arange(-width, width, dx)
Y = np.arange(-width, width, dx)
X, Y = np.meshgrid(X, Y)
Z = []
for i in range(len(X)):
    Z.append(np.zeros(len(X[i])))

But when I try to run Axes3D.plot_wireframe(X,Y,Z) I get plot_wireframe() missing 1 required positional argument: 'Z'. I need help understanding why this is, because Z is a 2D array like it should be, and I can't find many helpful examples with 3D plotting with matplotlib.

Upvotes: 0

Views: 1185

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

The main point is that you cannot run Axes3D.plot_wireframe(X,Y,Z) by itself. Instead you need to create an instance of Axes3D and call its method [*]. Just like in the 2D case where you wouldn't call matplotlib.axes.Axes.plot(x,y) but ax.plot(x,y) where ax is the instance created e.g. via fig.add_subplot.

An example for the wireframe plot can be found here.

The following code (using the code from the question)

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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

width = 1
dx = 0.1
X = np.arange(-width, width, dx)
Y = np.arange(-width, width, dx)
X, Y = np.meshgrid(X, Y)
Z = []
for i in range(len(X)):
    Z.append(np.zeros(len(X[i])))

ax.plot_wireframe(X, Y, Z)

plt.show()

produses the following plot

enter image description here


[*] To be precise here; you can call the class method plot_wireframe, but you would then need to supply it with the instance like

Axes3D.plot_wireframe(ax, X, Y, Z)

Upvotes: 2

DavedeKoning
DavedeKoning

Reputation: 190

I found this example online. I've pasted it in your code example and I got the following code + plot:

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

width = 1
dx = 0.1
X = np.arange(-width, width, dx)
Y = np.arange(-width, width, dx)
X, Y = np.meshgrid(X, Y)
Z = []
for i in range(len(X)):
    Z.append(np.zeros(len(X[i])))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.plot_wireframe(X, Y, Z)

plt.show()

enter image description here

Hope this helps! I ran it with python 3.5, using the spyder IDE.

Cheers, Dave

Upvotes: 1

Related Questions