pythonnumpyplot3d

python mathplotlib: 3D plots error: "ValueError: Argument Z must be 2-dimensional."


I'm new at coding but i was wondring why this piece of code isn't working. I get the error: "ValueError: Argument Z must be 2-dimensional."

Can someone help solving my problem? Thx S.B.

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

ax = plt.axes(projection= '3d')

def z_function(x,y):
    return m/(4*np.pi*r**3)*(3*m*r**2-m)
x = np.linspace(-10,10,100)
y = np.linspace(-10,10,100)
r = x**2+y**2
m = 10

X, Y = np.meshgrid(x,y)
Z = z_function(X,Y)

ax.plot_surface(X,Y,Z)
plt.show()

Solution

  • The reason your code failed is that you generate r as a 1-D array.

    To generate it as a 2-D array, run:

    r = x**2 + y[:, np.newaxis]**2
    

    The rest of your code is OK.

    Consider also such detail: Your z_function uses neither x nor y. Why did you include these parameters?