Home > Net >  how do I close figure in matplotlib? - python
how do I close figure in matplotlib? - python

Time:09-10

import matplotlib.pyplot as plt
import pandas as pd

l1 = [1, 2, 3, 4]
l2 = [2, 4, 6, 8]

fig = plt.figure()

def func():
    plt.pause(1)
    plt.plot(l1, l2)
    plt.draw()
    plt.pause(1)
    input("press any key to continue...")
    plt.close(fig)
    plt.pause(1)

while True:
    func()
    plt.pause(1)

If I don't use while True loop, it stops running as I press any key and that was my intention. However, if I run this code with while True loop, the figure window doesn't close even though I press any key or x button in the upper left. I think it is due to while True. I have no idea how to solve this problem, keeping while True.

CodePudding user response:

The issue is not while True: as much as how you create your figures. Let's step through your process conceptually:

  1. fig = plt.figure() creates a figure and stores the handle in fig.
  2. Then you call func, which draws on the figure and eventually calls plt.pause(1).
  3. You loop around and call func again. This time, plt.plot(l1, l2) creates a new figure, since there are no open figures.
  4. func calls plt.close(fig). But the handle that's stored in fig is not the new figure that you opened, so of course your figure won't close.

To close the correct figure, open the figure inside func. Using the object oriented API gives you more control regarding what you open, close, plot, etc:

import matplotlib.pyplot as plt
import pandas as pd

l1 = [1, 2, 3, 4]
l2 = [2, 4, 6, 8]

def func():
    fig, ax = plt.subplots()
    ax.plot(l1, l2)
    plt.show(block=False)
    plt.pause(1)
    input("press any key to continue...")
    plt.close(fig)
    plt.pause(1)

while True:
    func()

CodePudding user response:

Everytime a new loop executes, a new window is being created. You can close this window, but a new one will reapear immediatly.

  • Related