[Python] Plot a Torus with Python

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    I'm new in python and I'm trying to draw a Torus. I want my torus to look like the one here, but my following code doesn't work.

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

    # Parameters for the torus
    R = 2 # Major radius
    r = 1 # Minor radius

    # Create a meshgrid for u (angle around the main circle) and v (angle around the tube)
    u = np.linspace(0, 2 * np.pi, 100)
    v = np.linspace(0, 2 * np.pi, 50)
    u, v = np.meshgrid(u, v)

    # Parametric equations for the torus
    x = (R + r * np.cos(v)) * np.cos(u)
    y = (R + r * np.cos(v)) * np.sin(u)
    z = r * np.sin(v)

    # Plotting
    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot(111, projection='3d')

    # Torus surface
    ax.plot_surface(x, y, z, rstride=1, cstride=1, color='lightblue', edgecolor='gray', alpha=0.6)

    # Add lines of latitude (constant v, varying u)
    for j in np.linspace(0, 2*np.pi, 12): # meridians
    x_line = (R + r * np.cos(j)) * np.cos(u[0])
    y_line = (R + r * np.cos(j)) * np.sin(u[0])
    z_line = r * np.sin(j) * np.ones_like(u[0])
    ax.plot(x_line, y_line, z_line, color='darkblue', linewidth=1)

    # Add lines of longitude (constant u, varying v)
    for i in np.linspace(0, 2*np.pi, 12): # parallels
    x_line = (R + r * np.cos(v[:, 0])) * np.cos(i)
    y_line = (R + r * np.cos(v[:, 0])) * np.sin(i)
    z_line = r * np.sin(v[:, 0])
    ax.plot(x_line, y_line, z_line, color='darkred', linewidth=1)

    # Set aspect and remove axes
    ax.set_box_aspect([1, 1, 1])
    ax.axis('off')
    plt.title("Torus with Parallels and Meridians")
    plt.show()


    How can I draw a torus in this fashion?

    Continue reading...

Compartilhe esta Página