0

In the following code, I have defined a plt, but the show() function is called if a condition is met.

while True:
    # Get a key from keyboard and if it is 'q' exit the loop, otherwise do the following
    fig,axes = plt.subplots(2,1, figsize=(20, 15))
    should_plot = plot_dataframe(df, axes)
    if should_plot == True:
        for ax in axes:
            ax.legend()
        plt.show()

As you can see, plt.show() is not called always, however, the subplot() is called in each iteration of the loop. In the following situation

no plot
no plot
plot

I see three plot windows, two of them are empty and one shows the plot. Is there any way to delete the subplot on the else part?

P.S: The question is different form this topic. Here, I don't want to delete a subplot within a plot area. In fact the close() function is the right answer.

mahmood
  • 23,197
  • 49
  • 147
  • 242

1 Answers1

1

You can use plt.close() to close the current figure.

For instance, consider the following code:

import matplotlib.pyplot as plt

for i in range(4):

    fig, ax = plt.subplots()

    ax.plot([1,2],[1,2])
    plt.title(f"plot {i+1}")

    if (i+1) % 2 == 0:
        plt.show()
    else:
        plt.close()

If you run, you'll see "plot 2" and "plot 4". However, if you remove the "else" and "close", "plot 1" will show up at the same time as "plot 2", and the same with 3 and 4.

fdireito
  • 1,709
  • 1
  • 13
  • 19