1

Background

With the help of the following, I have created a dynamically updating plot

Dynamically updating plot in matplotlib

Updating a plot in python's matplotlib

How to update a plot in matplotlib?

Plot code

plt.ion()
fig_analysis = plt.figure()
for i in range(5):
    ax = fig_analysis.add_subplot(211)    
    l1, = ax.plot(np.linspace(0, 200, simulation_time), variable_1)
    ax.set_ylabel(r'$Variable\ 1$')
    ax = fig_analysis.add_subplot(212)
    l2, = ax.plot(np.linspace(0, 200, simulation_time), variable_2)
    ax.set_ylabel(r'$Variable\ 2$')
    ax.set_xlabel(r'$years$')
    fig_analysis.canvas.draw()
    plt.pause(0.5)

Behaviour

This code creates a plot and updates it. However, it closes the final plot after completion of the loop

Question

How should I modify the code to ensure that at the end of the loop, the program doesn't close the plot window, and I can save the image as I want.

Manual solution

One of the ways of achieving this is to manually pause the program. However, as runtime of my program is not fixed, it is difficult to implement this strategy.

Neeraj Hanumante
  • 1,575
  • 2
  • 18
  • 37

1 Answers1

1

Add

plt.ioff()    # turn interactive mode off
plt.show()

at the end of the code.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712