How could I close a plot in python and then reopen it?

断了今生、忘了曾经 提交于 2019-12-11 19:47:50

问题


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('Profit')
plt.yticks(np.arange(10000,25000,step=1500))
plt.title('Profit Chart')
play = True
while play:
  x = int(input("State your choise : "))
  if x == 3:
    plt.show()
  print("Would you like to continue? YES or NO?")
  y = input()
  if y == "NO":
    play = False
  plt.close("all")

And it seems like it doesn't close the plot at all. Not with close('all') ,nor with close(). What I'd like is to be able to open it and keep it open until the user states his answer, and afterwards ,close it. Any help? :D


回答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 = True
while 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")


来源:https://stackoverflow.com/questions/52843250/how-could-i-close-a-plot-in-python-and-then-reopen-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!