【问题标题】:How to make multiple views with a for loop with matplotlib in python?如何在 python 中使用带有 matplotlib 的 for 循环创建多个视图?
【发布时间】:2021-03-26 11:38:34
【问题描述】:

我需要在 python 中使用 matplotlib 制作 100 个视图。起点总是随机的。我知道如何生成 100 个图,但我想使用“前进到下一个视图”箭头。

这是我的代码:

import matplotlib.pyplot as plt


for i in range (1,3):

    Startx = [randrange(1, 19)]  # x axis values
    Starty = [randrange(1, 8)]  # y axis values

    plt.plot(Startx, Starty, color='black', linestyle='solid', linewidth=3,  # plotting the points
             marker='o', markerfacecolor='green', markersize=8)

    ##########################################################################################################
    Endx = [16.5]
    Endy = [7.5]

    plt.plot(Endx, Endy, color='black', linestyle='solid', linewidth=3,
             marker='o', markerfacecolor='red', markersize=8)

    ##########################################################################################################

    Ax = [5, 2.5, 3, 5, 6, 5]
    Ay = [7.5, 6, 3.5, 3, 5.5, 7.5]

    plt.plot(Ax, Ay, color='black', linestyle='solid', linewidth=3,
             marker='o', markerfacecolor='blue', markersize=8)

    ##########################################################################################################

    Bx = [8, 6.5, 7.25, 8]
    By = [3, 3, 5.5, 3]

    plt.plot(Bx, By, color='black', linestyle='solid', linewidth=3,
             marker='o', markerfacecolor='blue', markersize=8)

    plt.xlim(0, 19)
    plt.ylim(0, 8)  # setting x and y axis range

    plt.xlabel('x - axis')  # naming the x axis
    plt.ylabel('y - axis')  # naming the y axis

    plt.show()  # function to show the plot

【问题讨论】:

    标签: python matplotlib plot graph


    【解决方案1】:

    您可以尝试本文中提到的这种方法 matplotlib hooking in to home/back/forward button events 不要覆盖“主页”按钮,而是使用“前进”按钮。

    另见这个小例子。每次按下“前进到下一个视图”按钮,绘图都会更新一些随机数据。

    from matplotlib.backends.backend_tkagg import NavigationToolbar2Tk
    import matplotlib.pyplot as plt
    from random import randint
    
    #new forward button callback => gets triggered, when forward button gets pushed
    def customForward(*args):
        ax = plt.gca()
        fig = plt.gcf()
        
        #get line object...
        line = ax.get_lines()[0]
        
        #...create some new random data...
        newData = [randint(1, 10), randint(1, 10), randint(1, 10)]
        
        #...and update displayed data
        line.set_ydata(newData)
        ax.set_ylim(min(newData), max(newData))
        #redraw canvas or new data won't be displayed
        fig.canvas.draw()
    
    #monkey patch forward button callback
    NavigationToolbar2Tk.forward = customForward
    
    #plot first data
    plt.plot([1, 2, 3], [1, 2, 3])
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2022-07-07
      • 1970-01-01
      • 2015-09-16
      • 2019-03-07
      • 1970-01-01
      • 2020-07-23
      • 2022-01-10
      • 2021-01-10
      • 2021-01-06
      相关资源
      最近更新 更多