【发布时间】:2019-12-23 07:52:53
【问题描述】:
我正在运行一个循环来使用 Seaborn、Pandas 和 Python 提取数据和图表。我只想将每个绘图保存为图形并关闭它,但我无法弄清楚如何执行此操作。
/usr/local/lib/python3.6/dist-packages/seaborn/axisgrid.py:311:RuntimeWarning:已打开20多个图形。通过 pyplot 接口 (matplotlib.pyplot.figure) 创建的图形会一直保留到显式关闭,并且可能会消耗太多内存。 (要控制此警告,请参阅 rcParam figure.max_open_warning)。
我原以为 g.close() 可以工作,但我得到了错误: AttributeError: 'FacetGrid' 对象没有属性 'close'
for o in options:
s = "SELECT * from options_yahoo where contract_name = '" + o + "'
SQL_Query = pd.read_sql_query(s, conn)
df = pd.DataFrame(SQL_Query)
g = sns.relplot( kind="line", data=df[['bid','ask','lastprice']])
g.savefig( o+ ".png")
g.close()
我希望能够有一个更高效的解决方案,不会占用太多内存并带来警告错误。一些最佳实践将不胜感激。
【问题讨论】:
-
您需要访问图本身才能关闭:
g.fig.close() -
@busybear
g.fig.close()产生AttributeError: 'Figure' object has no attribute 'close'。请改用plt.close(g.fig),请参阅下面的答案。