Generating cobweb plots and bifurcation diagrams

Here's some Python code for generating cobweb plots and bifurcation diagrams.

Importing a couple of libraries

In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

Generating a cobweb plot

In [2]:
def f(c,x): return x**2 + c
n = 100
c = -1.2
x0 = 1.23
x1 = x0
cobweb_xs = [x1]
cobweb_ys = [x1]
for i in range(n):
    x2 = f(c,x1)
    cobweb_xs.append(x1)
    cobweb_ys.append(x2)
    x1 = x2
    cobweb_xs.append(x1)
    cobweb_ys.append(x2)
graph_xs = np.linspace(-2,2,100)
graph_ys = f(c, graph_xs)
start = x1
end = x2

for i in range(1,len(cobweb_xs)):
    plt.plot([cobweb_xs[i-1],cobweb_xs[i]],[cobweb_ys[i-1],cobweb_ys[i]],'k', alpha=0.2, linewidth=0.5)
plt.plot([-2,2],[-2,2], 'k', linewidth=2)
plt.plot(graph_xs,graph_ys, 'k', linewidth=3)
plt.plot(x0,x0, 'go', zorder=5)
plt.plot(x2,x2, 'ro', zorder=5)

ax = plt.gca()
ax.set_aspect(1)
ax.set_ylim(-2,2)
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlim(-2,2)

fig = ax.figure
fig.set_figwidth(8)
fig.set_figheight(8)

Generating a bifurcation diagram

In [3]:
def f(c,x): return x**2 + c

ax = plt.subplot(1,1,1)
ax.set_xlim(-2,0)
ax.set_ylim(-2,2)
c_data = []
x_data = []
for c in np.linspace(-2,0,2000):
    x = 0.0
    for i in range(100):
        x = f(c,x)
    for i in range(500):
        x = f(c,x)
        c_data.append(c)
        x_data.append(x)
plt.plot(c_data,x_data,'k.', alpha=0.2, markersize=0.3)

ax.set_xticks([-2,-1.4,-1.25,-0.75,0])
ax.set_yticks([-2,2]);

fig = ax.figure
fig.set_figwidth(13)
fig.set_figheight(8)