【问题标题】:Changing r values for cobweb diagrams in Python在 Python 中更改蜘蛛网图的 r 值
【发布时间】:2020-06-27 11:34:41
【问题描述】:

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)

【问题讨论】:

    标签: python matplotlib interactive arrow-keys


    【解决方案1】:

    您需要用plt.ion() 开启interactive mode,并用fig.canvas.draw() 替换plt.show()。检查以下代码:

    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)
    

    ,您将得到如下图:

    注意:如果您使用 linspace by scipy,则会收到以下警告:

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

    替换它是明智的
    from numpy import linspace
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多