python - matplotlib: efficient way to create large number of Patch objects -
i have python code plots large number of non-regular polygons using matplotlib ocean model data.
i creating 4 numpy arrays of shape (n,2) defining corners of each patch, n large number (say 500,000)
i create matplotlib patch object each set of corners , add list. finally, create matplotlib patchcollection object list of patches.
the problem patch generation slow because in loop. i've been trying think of way speed numpy broadcasting, can't quite crack it.
here's example code, small test dataset (which fast run).
import numpy np matplotlib.collections import patchcollection import matplotlib.pyplot plt # cell lat/lon centers: lons = np.array([ 323.811, 323.854, 323.811, 323.723, 324.162, 324.206, 323.723, 324.162, 323.635, 323.679]) lats = np.array([-54.887, -54.887, -54.858, -54.829, -54.829, -54.829, -54.799, -54.799, -54.770, -54.770]) # cell size scaling factors: cx = np.array([1,1,1,2,2,2,4,1,2,1]) cy = np.array([1,1,1,1,2,2,2,1,2,1]) # smallest cell sizes: min_dlon = 0.0439453 min_dlat = 0.0292969 # calculate cell sizes based on cell scaling factor , smallest cell size dlon = cx * min_dlon dlat = cy * min_dlat # calculate cell extnets.... x1 = lons - 0.5 * dlon x2 = lons + 0.5 * dlon y1 = lats - 0.5 * dlat y2 = lats + 0.5 * dlat # ... , corners c1 = np.array([x1,y1]).t c2 = np.array([x2,y1]).t c3 = np.array([x2,y2]).t c4 = np.array([x1,y2]).t # loop on cells , create patch objects cell corners. # bottleneck using slow python loop instead of # fast numpy broadcasting. how can speed up? ncel = np.alen(lons) patches = [] in np.arange(ncel): verts = np.vstack([c1[i], c2[i], c3[i], c4[i]]) p = plt.polygon(verts) patches.append(p) # create patch collection list of patches p = patchcollection(patches, match_original=true) is there way can speed up?
what create collection matplolib.collections instead of creating every polygon (or patch)? @ examples here: http://matplotlib.org/examples/api/collections_demo.html
and read matplotlib documentation: http://matplotlib.org/api/collections_api.html?highlight=polycollection#matplotlib.collections.polycollection
this example code add 200,000 polygons ~10s:
import numpy np import matplotlib.pyplot plt matplotlib.collections import polycollection import matplotlib npol, nvrts = 200000, 5 cnts = 100 * (np.random.random((npol,2)) - 0.5) offs = 10 * (np.random.random((nvrts,npol,2)) - 0.5) vrts = cnts + offs vrts = np.swapaxes(vrts, 0, 1) z = np.random.random(npol) * 500 fig, ax = plt.subplots() coll = polycollection(vrts, array=z, cmap=matplotlib.cm.jet) ax.add_collection(coll) ax.autoscale() plt.show() 
Comments
Post a Comment