I was trying to create a bifurcation diagram using pyplot in Python 3. I first defined a function for the logistic map and then used it in a second function in a for loop to generate the bifurcation diagram. The following is my code:
import numpy as np
import matplotlib.pyplot as plt
def logistic(n, r, x0):
xn = []
for i in range(1,n+1):
x0 = r*x0*(1-x0)
xn += [x0]
xn = np.array(xn)
return xn
def bifurcation(n, k, rmin, rmax, rstep, x0):
for r in np.arange(rmin, rmax, rstep):
traj = logistic(n, r, x0)
R = r*np.ones([1, n+1])
plt.scatter(R[k:n], traj[k:n])
plt.xlim([rmin, rmax])
plt.ylim([0, 1])
plt.show()
bifurcation(50, 5, 2.4, 4, 0.1, 0.2)
The problem is that I get a blank plot as the output. No points are plotted at all. What am I doing wrong here?
import numpy as np
import matplotlib.pyplot as plt
def logistic(n, r, x0):
xn = []
for i in range(1,n+1):
x0 = r*x0*(1-x0)
xn += [x0]
xn = np.array(xn)
#print(xn.shape)
return xn
def bifurcation(n, k, rmin, rmax, rstep, x0):
for r in np.arange(rmin, rmax, rstep):
traj = logistic(n, r, x0)
R = r*np.ones(shape=n)
plt.scatter(R[k:n], traj[k:n])
#print(R.shape)
plt.xlim([rmin, rmax])
plt.ylim([0, 1])
plt.show()
bifurcation(50, 5, 2.4, 4, 0.1, 0.2)
you forgot tabs in logistic() and np.ones vas a bit strange
When I first ran your code, I noticed that R[k:n]
and traj[k:n]
were both empty. It turns out that you've defined R
such that there is a list inside of a list, and it's the inner list that has the numbers.
Thus, I just grabbed the inner list rather than using the outer one. So R = r*np.ones([1, n+1])
became R = r*np.ones([1, n+1])[0]
. (There may be a more elegant way of doing this, but this should suffice.)
Then, for traj
, it looks like traj only computes a single number (and puts it inside of a list), but in order to graph information, you need to have each of the x
and y
lists for the scatter
function to have the right size. So I just duplicated the single number as many times as needed ( nk
times). So traj[k:n]
should instead be [traj[0]] * (nk)
.
Here's the full code:
import numpy as np
import matplotlib.pyplot as plt
def logistic(n, r, x0):
xn = []
for i in range(1,n+1):
x0 = r*x0*(1-x0)
xn += [x0]
xn = np.array(xn)
return xn
def bifurcation(n, k, rmin, rmax, rstep, x0):
for r in np.arange(rmin, rmax, rstep):
traj = logistic(n, r, x0)
R = r*np.ones([1, n+1])[0]
R_list = R[k:n]
traj_list = [traj[0]] * (n-k)
plt.scatter(R_list, traj_list)
plt.xlim([rmin, rmax])
plt.ylim([0, 1])
plt.show()
bifurcation(50, 5, 2.4, 4, 0.1, 0.2)
Not sure if this is what you were looking for, but it seems to solve your problem of not getting a graph to show up. Hopefully it's helpful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.