如何在python-ggplot中删除图形?

0 投票
1 回答
1605 浏览
提问于 2025-04-18 01:58

Python的ggplot库真不错,但我遇到了一个内存问题。

import pandas as pd
from ggplot import *


data = pd.DataFrame({"date": [1, 2, 3],
                     "value": [10, 20, 30]})

for i in range(30):
    gg = ggplot(aes(x='date', y='value'), data=data) + geom_point(alpha=0.5)
    print(gg)
    f = "fig{}.png".format(i)
    ggsave(f, gg)

这段代码会显示一个运行时警告(ggplot-0.4.7)。

/lib/python2.7/site-packages/matplotlib/pyplot.py:412: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_num_figures`).

我该怎么删除旧的图形呢?

1 个回答

2

ggplot使用的是matplotlib的pyplot接口。你可以用下面的代码关闭所有已经打开的pyplot图形:

# Importing this library as plt is a convention, same
# importing numpy as np, or pandas as pd
import matplotlib.pyplot as plt
plt.close('all')

ggplot目前还处于开发的早期阶段,所以希望随着它逐渐接近稳定版本,这些问题会得到解决。

撰写回答