2016-05-20 35 views
0

我需要繪製一大堆不同的物體(〜10^5填充橢圓和相似的形狀)。我所做的是使用命令plt.gcf()。gca()。add_artist(e)一次添加一個,然後在最後使用plt.show()。這需要比我有更多的記憶。如何避免在Python繪圖中耗盡內存?

有沒有辦法一次繪製它們(也就是說,沒有像上面那樣添加它們),從而減少了我消耗的內存量?即使使用了大大增加繪圖所需時間的解決方案,我也可以。

+0

如果你只是保存在最後的數字,而不是使用mpl呈現它怎麼辦? – pbreach

+0

['matplotlib.collections'](http://matplotlib.org/api/collections_api.html#module-matplotlib.collections)用於共享大多數屬性的大量對象的***高效***繪圖的類[ ...] - 重點是我的 – gboffi

回答

1

吸引你必須使用不同的matplotlib.collections類的一個相似的對象量大 - 唉,它們的使用是有點神祕,至少當它是我的理解是參與......

不管怎麼說從docsthis official example 開始我能夠整理出以下代碼

$ 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秒鐘 - 結果是什麼?

el10^5.png

我認爲,關於偏心和角度的細節在如此密集的表示都輸了,但我不知道你的任務的細節,也不會發表進一步的評論。