簡體   English   中英

為什么我在使用 matplotlib 時得到一個空的 plot?

[英]Why do I get an empty plot while using matplotlib?

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. 以下是我的代碼:

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)

問題是我得到一個空白的 plot 作為 output。 根本沒有繪制任何點。 我在這里做錯了什么?

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)

你忘記了logistic()和np.ones vas中的標簽有點奇怪

當我第一次運行您的代碼時,我注意到R[k:n]traj[k:n]都是空的。 事實證明,您已經定義R以便在列表內部有一個列表,並且它是具有數字的內部列表。

因此,我只是抓住了內部列表而不是使用外部列表。 所以R = r*np.ones([1, n+1])變成R = r*np.ones([1, n+1])[0] (可能有一種更優雅的方式來做到這一點,但這應該就足夠了。)

然后,對於traj ,看起來 traj 只計算一個數字(並將其放在列表中),但為了繪制信息,您需要擁有scatter function 的每個xy列表才能擁有正確的尺寸。 所以我只是根據需要多次復制單個數字( nk次)。 所以traj[k:n]應該改為[traj[0]] * (nk)

然后我們得到一個圖表: 代碼工作圖

這是完整的代碼:

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)

不確定這是否是您想要的,但它似乎解決了您沒有顯示圖表的問題。 希望它會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM