[英]How to avoid running out of memory in Python plotting?
我需要繪制大量不同的對象(〜10 ^ 5個填充的橢圓和類似形狀)。 我要做的是使用命令plt.gcf()。gca()。add_artist(e)一次添加一個,然后最后使用plt.show()。 這需要比我更多的內存。
有沒有一種方法可以一次繪制它們(即,不像我上面那樣添加它們),從而減少我消耗的內存量? 即使使用可以顯着增加繪圖所需時間的解決方案,我也可以。
要繪制大量相似的對象,您必須使用不同的matplotlib.collections
類之一matplotlib.collections
,至少在涉及我的理解時,它們的用法有點不可思議。
無論如何,從文檔和這個官方示例開始,我能夠將以下代碼放在一起
$ cat ellipses.py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import EllipseCollection
N = 10**5
# centres of ellipses — uniform distribution, -5<=x<5, -3<=y<3
xy = np.random.random((N,2))*np.array((5*2,3*2))-np.array((5,3))
# width, height of ellipses
w, h = np.random.random(N)/10, np.random.random(N)/10
# rotation angles, anticlockwise
a = np.random.random(N)*180-90
# we need an axes object for the correct scaling of the ellipses
fig, ax = plt.subplots()
# create the collection
ec = EllipseCollection(w, h, a,
units='x',
offsets=xy,
transOffset=ax.transData)
ax.add_collection(ec)
ax.autoscale(tight=True)
plt.savefig('el10^5.png')
我在幾乎低端的筆記本電腦上計時
$ time python -c 'import numpy; import matplotlib.pyplot as p; f, a = p.subplots()'
real 0m0.697s
user 0m0.620s
sys 0m0.072s
$ time python ellipses.py
real 0m5.704s
user 0m5.616s
sys 0m0.080s
$
如您所見,如果您不考慮每個情節所需的登台,則大約需要5秒鍾-結果是什么?
我認為關於偏心距和角度的詳細信息在如此密集的描述中會丟失,但是我不知道您的任務的細節,因此不再贅述。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.