1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Can I create a sphere in matplotlib with all inputs 3d (e.g. x**2 + y**2 + z**2 = 0)

Discussão em 'Python' iniciado por Stack, Setembro 10, 2025.

  1. Stack

    Stack Membro Participativo

    I want to create a fun (for me ;-)) Python project where I plot mathematical formulas in 3d using matplotlib and I was especially looking to print a sphere, since a line is a quite boring formula (y = x + z) and even parabolas can be boring (y = x^2 + z^2). But a sphere x^2 + y^2 + z^2 = 0 directly interested me.

    Using Matplotlib trying to draw a circle though basic equation ( x**2 + y**2 = 9) as a basis I run into an issue when I do the following:

    x = np.linspace(-5.0, 5.0, 100) # 1000 takes too much memory :cool:
    y = np.linspace(-5.0, 5.0, 100)
    z = np.linspace(-5.0, 5.0, 100)

    X, Y, Z = np.meshgrid(x,y,z)
    F = X**2 + Y**2 + Z**2 -9
    fig, ax = plt.subplots()

    # up to here everything worked, but the next line(s) give all the same error which is the one I want to overcome:
    ax.contour(X,Y,Z,F) # or
    ax.contour(X,Y,F,[0]) # and even the following
    ax.contour(X,Y,F)


    The error I get is:

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "D:\Python\Python312\Lib\site-packages\matplotlib\__init__.py", line 1524, in inner
    return func(
    ^^^^^
    File "D:\Python\Python312\Lib\site-packages\matplotlib\axes\_axes.py", line 6779, in contour
    contours = mcontour.QuadContourSet(self, *args, **kwargs)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "D:\Python\Python312\Lib\site-packages\matplotlib\contour.py", line 701, in __init__
    kwargs = self._process_args(*args, **kwargs)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "D:\Python\Python312\Lib\site-packages\matplotlib\contour.py", line 1319, in _process_args
    x, y, z = self._contour_args(args, kwargs)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "D:\Python\Python312\Lib\site-packages\matplotlib\contour.py", line 1359, in _contour_args
    x, y, z = self._check_xyz(x, y, z_orig, kwargs)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "D:\Python\Python312\Lib\site-packages\matplotlib\contour.py", line 1385, in _check_xyz
    raise TypeError(f"Input z must be 2D, not {z.ndim}D")


    So now my question is: is there a way to make this code work (so a 3d plot of a sphere) or am I just trying to do something which cannot be done using matplotlib? And if it is possible, what am I doing wrong? (It is either in F, since all 3 ax.contour definitions fail. Or in the definition of z, since F contains the meshgrid of z)

    Continue reading...

Compartilhe esta Página