Plotting Fibonacci Spiral with Python

Fibonacci spiral with Python and Matplotlib

Oliver Lövström
Internet of Technology
3 min readJan 31, 2024

--

In the last article, we challenged ourselves to improve the Fibonacci project with a Fibonacci spiral plot. You can check out the Fibonacci generator here:

Photo by Getty Images on Unsplash

To implement the Fibonacci spiral, we are using Matplotlib. Alternatively, you can try using Turtle. See this GeeksforGeeks article: Plotting Fibonacci spiral fractal using Turtle.

Solution

Here’s a quick overview of our approach:

def plot_fibonacci(sequence: list[int]) -> None:
"""Plot Fibonacci spiral.

:param sequence: Fibonacci sequence.
"""
# Calculate the golden ratio
golden_ratio = sequence[-1] / sequence[-2]

# Generate angles for the spiral
angles = np.linspace(0, 8 * np.pi, num=len(sequence))

# Calculate radius for logarithmic spiral
radius = golden_ratio ** (angles / np.pi)

# Convert to Cartesian coordinates
x = radius * np.cos(angles)
y = radius * np.sin(angles)

# Create the plot
plt.figure(figsize=(8, 8))
plt.plot(x, y, color="blue", linewidth=2)
plt.axis("equal")
plt.axis("off")
plt.show()

Let’s break down the code step by step:

  • Firstly, we calculate the golden ratio from our Fibonacci sequence.
  • Then, we generate a series of angles to represent the spiral.
  • We transform these angles into a spiral path by calculating the radius for a logarithmic spiral.
  • Finally, we plot these points using Matplotlib to visualize the Fibonacci spiral.

Full Code

We’ve implemented this new plotting function into our existing code:

import numpy as np
from matplotlib import pyplot as plt


def fibonacci(length: int) -> list[int]:
"""Generate Fibonacci sequence.

:param length: The length of the Fibonacci sequence.
:return: The Fibonacci sequence of length.
"""
if length <= 0:
return []

if length == 1:
return [0]

sequence = [0, 1]
while len(sequence) < length:
next_number = sequence[-1] + sequence[-2]
sequence.append(next_number)

return sequence


def plot_fibonacci(sequence: list[int]) -> None:
"""Plot Fibonacci spiral.

:param sequence: Fibonacci sequence.
"""
# Calculate the golden ratio
golden_ratio = sequence[-1] / sequence[-2]

# Generate angles for the spiral
angles = np.linspace(0, 8 * np.pi, num=len(sequence))

# Calculate radius for logarithmic spiral
radius = golden_ratio ** (angles / np.pi)

# Convert to Cartesian coordinates
x = radius * np.cos(angles)
y = radius * np.sin(angles)

# Create the plot
plt.figure(figsize=(8, 8))
plt.plot(x, y, color="blue", linewidth=2)
plt.axis("equal")
plt.axis("off")
plt.show()


def main() -> None:
"""Main function."""
while True:
try:
length = int(input("Enter the length of the Fibonacci sequence: "))
if length < 0:
print("Please enter a non-negative integer.")
else:
break
except ValueError:
print("Please enter a valid integer.")

sequence = fibonacci(length)
print("Fibonacci sequence of length", length, ":", sequence)
plot_fibonacci(sequence)


if __name__ == "__main__":
main()

Testing the Plotting

To test the updated script, simply run the following:

$ python fibonacci.py
Image by Author

Wrapping Up

Congratulations on reaching this point! You’ve plotted the Fibonacci spiral and also expanded your Python skills. Discover all the code from this series on Python Projects on GitHub.

Further Reading

If you want to learn more about programming and, specifically, Python and Java, see the following course:

Note: If you use my links to order, I’ll get a small kickback. So, if you’re inclined to order anything, feel free to click above.

--

--