如何在python中关闭图并重新打开它? [英] How could I close a plot in python and then reopen it?

查看:305
本文介绍了如何在python中关闭图并重新打开它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下代码:

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

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

推荐答案

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

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.

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

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.

举个例子:

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

这篇关于如何在python中关闭图并重新打开它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆