2012-10-14 94 views
20

我想使用matplotlib和底图在地图上绘制大约60000个形状(每个角的纬度/经度坐标)的日期集。使用matplotlib更高效地绘制多边形

这是我目前做的方式:

for ii in range(len(data)): 
    lons = np.array([data['lon1'][ii],data['lon3'][ii],data['lon4'][ii],data['lon2'][ii]],'f2') 
    lats = np.array([data['lat1'][ii],data['lat3'][ii],data['lat4'][ii],data['lat2'][ii]],'f2') 
    x,y = m(lons,lats) 
    poly = Polygon(zip(x,y),facecolor=colorval[ii],edgecolor='none') 
    plt.gca().add_patch(poly) 

然而,这需要我的机器上大约1.5分钟,我在想是否有可能加快速度一点。有没有更有效的方法来绘制多边形并将其添加到地图?

回答

31

您可以考虑创建多边形集合而不是单个多边形。

相关的文档可以在这里找到:http://matplotlib.org/api/collections_api.html 有了一个例子值得拿起APPART这里:http://matplotlib.org/examples/api/collections_demo.html

举个例子:

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib.collections import PolyCollection 
import matplotlib as mpl 

# Generate data. In this case, we'll make a bunch of center-points and generate 
# verticies by subtracting random offsets from those center-points 
numpoly, numverts = 100, 4 
centers = 100 * (np.random.random((numpoly,2)) - 0.5) 
offsets = 10 * (np.random.random((numverts,numpoly,2)) - 0.5) 
verts = centers + offsets 
verts = np.swapaxes(verts, 0, 1) 

# In your case, "verts" might be something like: 
# verts = zip(zip(lon1, lat1), zip(lon2, lat2), ...) 
# If "data" in your case is a numpy array, there are cleaner ways to reorder 
# things to suit. 

# Color scalar... 
# If you have rgb values in your "colorval" array, you could just pass them 
# in as "facecolors=colorval" when you create the PolyCollection 
z = np.random.random(numpoly) * 500 

fig, ax = plt.subplots() 

# Make the collection and add it to the plot. 
coll = PolyCollection(verts, array=z, cmap=mpl.cm.jet, edgecolors='none') 
ax.add_collection(coll) 
ax.autoscale_view() 

# Add a colorbar for the PolyCollection 
fig.colorbar(coll, ax=ax) 
plt.show() 

enter image description here

HTH,

+13

希望这是正常的,我添加的例子! –

+0

Thx,很好的例子!我认为PolyCollection是关键。但是,我很困惑如何将我的lons/lats变成多边形。在你的情况“verts”。 – HyperCube

+0

@JoeKington:很好。不幸的是,我将得到你所有努力工作的荣誉... – pelson

3

我调整我的代码,现在它工作完美:)

这里是工作示例:

lons = np.array([data['lon1'],data['lon3'],data['lon4'],data['lon2']]) 
lats = np.array([data['lat1'],data['lat3'],data['lat4'],data['lat2']]) 
x,y = m(lons,lats) 
pols = zip(x,y) 
pols = np.swapaxes(pols,0,2) 
pols = np.swapaxes(pols,1,2) 
coll = PolyCollection(pols,facecolor=colorval,cmap=jet,edgecolor='none',zorder=2) 
plt.gca().add_collection(coll) 
+3

完美而快速?你从原来的1.5分钟里存了多少时间? – pelson

+3

现在它需要32秒,所以它真的加快了速度! – HyperCube

+2

'm'是什么?添加导入/定义会很好。 –