更改 Python 中蛛网图的 r 值

Changing r values for cobweb diagrams in Python

Matplotlib 相对较新。我绘制了一个蜘蛛网图,现在希望通过箭头键更改 r 值,因为程序是 运行。尝试将“导入键盘”与“运行 循环”一起使用,但它似乎不起作用。有人可以解释一下吗?

import matplotlib.pyplot as plt
import keyboard
from scipy import linspace

r = 3.35
x0 = 0.3
running = True


def cobweb(f, x0):
    t = linspace(0, 1, 100)
    l = plt.plot(t, f(t))
    plt.plot(t, t)

    x, y = x0, f(x0)
    for _ in range(100):
        fy = f(y)
        plt.plot([x, y], [y, y], 'b', linewidth=1)
        plt.plot([y, y], [y, fy], 'b', linewidth=1)
        x, y = y, fy

    plt.xlabel("X n")
    plt.ylabel("X n+1")
    plt.show()
    plt.close()


while running:
    cobweb(lambda x: r * x * (1 - x), x0)
    if keyboard.is_pressed('up'):
        r += 0.1
    if keyboard.is_pressed('down'):
        r -= 0.1
    cobweb(lambda x: r * x * (1 - x), x0)

您需要将 interactive mode 设为 plt.ion(),将 plt.show() 设为 fig.canvas.draw()。检查以下代码:

import matplotlib.pyplot as plt
import keyboard
# from scipy import linspace
from numpy import linspace
import time

r = 3.35
x0 = 0.3
running = True


def cobweb(f, x0):
    ax.cla()
    t = linspace(0, 1, 100)
    l = plt.plot(t, f(t))
    plt.plot(t, t)

    x, y = x0, f(x0)
    for _ in range(100):
        fy = f(y)
        plt.plot([x, y], [y, y], 'b', linewidth=1)
        plt.plot([y, y], [y, fy], 'b', linewidth=1)
        x, y = y, fy

    plt.xlabel("X n")
    plt.ylabel("X n+1")
    fig.canvas.draw()
    time.sleep(0.01)

plt.ion()
fig, ax = plt.subplots()

while running:
    if keyboard.is_pressed('up'):
        r += 0.1
    if keyboard.is_pressed('down'):
        r -= 0.1
    cobweb(lambda x: r*x*(1 - x), x0)

,您将得到如下图:

注意:如果您通过 scipy 使用 linspace,您会收到此警告:

DeprecationWarning: scipy.linspace is deprecated and will be removed in SciPy 2.0.0, use numpy.linspace instead

换成

是明智的
from numpy import linspace

正如我在上面的代码中所做的那样。您的代码的功能不会改变