Getting Memory Error when trying to plot large array with matplotlib


Question

I would like to plot an array of 20 millions object, I have 8GB RAM and still I get the following error when I run the following lines:

import matplotlib.pyplot as plt
import numpy as np

d = np.arange(200000000)
plt.plot(d)
plt.show()

Error:

Traceback (most recent call last):
...
  File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 317, in _grab_next_args
    for seg in self._plot_args(remaining, kwargs):
  File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 292, in _plot_args
    x = np.arange(y.shape[0], dtype=float)
MemoryError
1
3
9/2/2011 2:05:37 PM

Due to physical limitations of displays and plotters, you won't be able to plot 20,000,000 points anyway. So you could reduce your array by sampling it or by using means of slices:

>>> m = 20000000
>>> a = np.arange(m)
>>> n = 100 # <- reducing to 100 points
>>> s = m/n # <- size of slices to compress
>>> reduced = []
>>> for i in xrange(n):
...     slice = a[i*s:(i+1)*s]
...     reduced.append(np.mean(slice))
>>> reduced
[99999.5, 299999.5, ..., 19699999.5, 19899999.5]

.. assuming np.mean makes sense on the objects you're plotting.

6
11/19/2016 2:00:09 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon