如何在python中关闭图并重新打开它?

时间:2018-10-16 20:03:07

标签: python python-3.x matplotlib plot charts

所以我有以下代码:

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

似乎完全没有关闭情节。不使用close('all'),也不使用close()。我想要的是能够将其打开并保持打开状态,直到用户说出答案为止,然后再将其关闭。 有什么帮助吗? :D

1 个答案:

答案 0 :(得分:0)

您的图未关闭的原因是因为plt.show()阻止了执行,因此您的代码甚至没有到达plt.close("all")行。要解决此问题,您可以在调用plt.show(block=False)之后使用show继续执行。

要重新打开图并按照您的预期工作,使其循环工作,需要将图创建逻辑移至while循环内。但是请注意,plt.style.use('bmh')不得放在此循环中。

这是一个例子:

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")
相关问题