Search code examples
pythonmathmatplotlibspiral

Drawing a logarithmic spiral in three axes in Python


I try to draw a logarithmic spiral in the form of a spring in three axes. Using the parametric equations:

x=a*exp(b*th)*cos(th)
y=a*exp(b*th)*sin(th)

Using the code:

import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
from math import exp,sin,cos
from pylab import *

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure()
ax = fig.gca(projection='3d')
n=100
a=0.5
b=0.20
th=np.linspace(0, 500, 10000)
x=a*exp(b*th)*cos(th)
y=a*exp(b*th)*sin(th)
ax.plot(x, y)
ax.legend()

plt.show()

I get:

enter image description here

However, I would like to stretch the spiral along the Z axis to get a result similar to the following, but using the logarithmic spiral as the basis:

enter image description here

How can you do it? How do you modify the function by adding a condition to the Z axis?


Solution

  • Since 95% of the points of the spiral are condensed in a single point in the middle of the plot it would make sense to restrict the plotted range to something like

    th=np.linspace(475, 500, 10000)
    

    Then using a linear range of z values would directly give you the desired curve in the plot, by simply specifying that range in the plot function, plot(x,y,z).

    from mpl_toolkits.mplot3d import Axes3D
    import numpy as np
    import matplotlib.pyplot as plt
    
    plt.rcParams['legend.fontsize'] = 10
    
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    
    a=0.5
    b=0.20
    th=np.linspace(475, 500, 10000)
    x=a*np.exp(b*th)*np.cos(th)
    y=a*np.exp(b*th)*np.sin(th)
    z = np.linspace(0,2, len(th))
    ax.plot(x, y, z)
    #ax.legend()
    
    plt.show()
    

    enter image description here

    Note that I cleaned up the imports here. E.g. if you import cos from math but later import everything (*) from pylab into the namespace, the function cos that is used is the numpy cos function, not the one from math (the math cos function would not work here anyways). In general: don't use pylab at all.