使用matplotlib更有效地绘制多边形

使用matplotlib更有效地绘制多边形

本文介绍了使用matplotlib更有效地绘制多边形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个约60000个形状的日期集(每个角的经/纬坐标),我想使用matplotlib和basemap在地图上绘制.

I have a dateset of around 60000 shapes (with lat/lon coordinates of each corner) which I want to draw on a map using matplotlib and basemap.

这是我目前的做法:

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分钟,我在想是否可以加快速度.有没有更有效的方法来绘制多边形并将其添加到地图?

However, this takes around 1.5 minutes on my machine and I was thinking whether it is possible to speed things up a little. Is there a more efficient way to draw polygons and add them to the map?

推荐答案

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

You could consider creating Collections of polygons instead of individual polygons.

相关文档可在此处找到: http://matplotlib.org/api/collections_api.html 这里有一个值得挑选的例子: http://matplotlib.org/examples/api/collections_demo.html

The relevant docs can be found here: http://matplotlib.org/api/collections_api.htmlWith a example worth picking appart here: 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()

HTH,

这篇关于使用matplotlib更有效地绘制多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 00:50