【问题标题】:How to close Seaborn plots如何关闭 Seaborn 地块
【发布时间】: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),请参阅下面的答案。

标签: python seaborn


【解决方案1】:

如果要关闭与名为 sns_plot 的 seaborn 图(例如 FacetGrid)相对应的特定图形,请使用:

plt.close(sns_plot.fig)

【讨论】:

    【解决方案2】:

    Seaborn plots 响应 pyplot 命令,你可以plt.close() 关闭当前图形,即使它是由 Seaborn 绘制的

    【讨论】:

    • 注意它是 plt.close() (matplotlib.pyplot) 而不是 sns.close()sns_plot.close() (seaborn)
    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    相关资源
    最近更新 更多