How do I close figure in matplotlib?

Question:

`

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)

`

This is the modified one:

`

import matplotlib.pyplot as plt
import pandas as pd
l1 = [1,2,3,4]
l2 = [2,4,6,8]
fig = plt.figure()
a = 1

def func(num):
    input(f"the {num}th window is not opened yet")
    plt.pause(1)
    plt.plot(l1,l2)
    plt.draw()
    print(f"the {num}th window is opened")
    plt.pause(1)
    input("press any key to continue...")
    plt.close(fig)
    plt.pause(1)
    print(f"the {num}th window is closed")
while True:
    func(a)
    plt.pause(1)
    a+=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. Please help me!

  • modified:
    I could see an opened window when "The 2th window is not opened yet" input message came out. Probably, the window would be the one from the first time of the loop, since the second window wasn’t opened at that time. Why was the first window still there? I used plt.close() to close the window.
Asked By: CoderHan

||

Answers:

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()

Alternatively, you can just replace plt.close(fig) with plt.close(), which is equivalent to plt.close(plt.gcf()), so you don’t have to know the handle to your new figure.

Answered By: Mad Physicist
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.