Matplotlib does not update plot when used in an IDE (PyCharm)

后端 未结 2 744
半阙折子戏
半阙折子戏 2021-01-06 02:04

I am new to python and just installed pyCharm and tried to run a test example given to the following question: How to update a plot in matplotlib?

This example upda

2条回答
  •  星月不相逢
    2021-01-06 02:27

    The updating in the linked question is based on the assumption that the plot is embedded in a tkinter application, which is not the case here.

    For an updating plot as a standalone window, you need to have turned interactive mode being on, i.e. plt.ion(). In PyCharm this should be on by default.

    To show the figure in interactive mode, you need to draw it, plt.draw(). In order to let it stay responsive you need to add a pause, plt.pause(0.02). If you want to keep it open after the loop has finished, you would need to turn interactive mode off and show the figure.

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.linspace(0, 6*np.pi, 100)
    y = np.sin(x)
    
    plt.ion()
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    line1, = ax.plot(x, y, 'r-') 
    plt.draw()
    
    for phase in np.linspace(0, 10*np.pi, 500):
        line1.set_ydata(np.sin(x + phase))
        plt.draw()
        plt.pause(0.02)
    
    plt.ioff()
    plt.show()
    

提交回复
热议问题