Skip to content Skip to sidebar Skip to footer

How Could I Close A Plot In Python And Then Reopen It?

So I have this code: plt.style.use('bmh') fig = plt.figure(figsize=(10,5)) ax = fig.add_subplot(111) ax.plot(months, monthly_profit, 'b-',lw=3) plt.xlabel('Monthhs') plt.ylabel('Pr

Solution 1:

The reason your plot does not close is because plt.show() blocks execution, so your code doesn't even reach the plt.close("all") line. To fix this you can use plt.show(block=False) to continue execution after calling show.

To reopen plots and have your loop work as I believe you are expecting it to, you need to move the plot creation logic to within the while loop. Note, however, that plt.style.use('bmh') must not be placed in this loop.

Here's an example:

import matplotlib.pyplot as plt
import numpy as np

# sample data
months = [1,2,3]
monthly_profit = [10, 20, 30]

plt.style.use('bmh')

play = Truewhile play:
  fig = plt.figure(figsize=(10,5))
  ax = fig.add_subplot(111)
  ax.plot(months, monthly_profit, 'b-',lw=3)
  plt.xlabel('Monthhs')
  plt.ylabel('Profit')
  plt.yticks(np.arange(10000,25000,step=1500))
  plt.title('Profit Chart')

  x = int(input("State your choise : "))
  if x == 3:
    plt.show(block=False)
  print("Would you like to continue? YES or NO?")
  y = input()
  if y == "NO":
    play = False
  plt.close("all")

Post a Comment for "How Could I Close A Plot In Python And Then Reopen It?"