# https://chatgpt.com/c/674df367-ed7c-8008-a5d6-a24fe07461ba

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np

# Parameters for the logistic map
r_values = np.linspace(2.5, 4.0, 300)  # Range of r values
n_iterations = 200  # Total iterations
n_last = 50  # Plot the last `n_last` iterations to show chaotic behavior

# Initialize figure and axis
fig, ax = plt.subplots()
ax.set_xlim(2.5, 4.0)
ax.set_ylim(0, 1)
ax.set_xlabel("r (growth rate)")
ax.set_ylabel("Population")
scatter, = ax.plot([], [], 'o', markersize=1, color='blue')

# Precompute iterations for the logistic map
def logistic_map(r, x):
    return r * x * (1 - x)

data = []

for r in r_values:
    x = 0.5  # Initial condition
    trajectory = []
    for i in range(n_iterations):
        x = logistic_map(r, x)
        if i >= n_iterations - n_last:
            trajectory.append((r, x))
    data.extend(trajectory)

data = np.array(data)
r_data, x_data = data[:, 0], data[:, 1]

# Animation update function
def update(frame):
    scatter.set_data(r_data[:frame], x_data[:frame])
    return scatter,

# Create the animation
ani = FuncAnimation(fig, update, frames=len(r_data), interval=1, blit=True)

plt.show()
