使用Shapely多边形进行映射
我现在遇到一个问题,想让下面的代码正常运行,但不知道该怎么做。出于某种原因,GeoPandas的*.plot()方法不管用,但我想同时使用Pandas和GeoPandas来做一些简单的图表。
我一直在尝试把GeoPandas中的Shapely对象拿出来,然后在Basemap上绘制它们。问题是,这些多边形根本画不出来。我从GeoPandas.geometry中一个个遍历这些多边形,把它们添加到坐标轴集合中,然后调用plot()方法,但就是没效果。Basemap看起来没问题,代码也没有报错,但这些多边形——县的边界——就是不显示出来……
谢谢你的帮助!
import geopandas as gpd
from descartes import PolygonPatch
import matplotlib as mpl
import mpl_toolkits.basemap as base
import matplotlib.pyplot as plt
counties_file = r'C:\Users\...\UScounties\UScounties.shp'
counties = gpd.read_file(counties_file)
#new plot
fig = plt.figure(figsize=(5,5),dpi=300)
#ax = fig.add_subplot(111)
ax = ax = plt.gca()
minx, miny, maxx, maxy = counties.total_bounds
#map
m = base.Basemap(llcrnrlon=minx, llcrnrlat=miny,
urcrnrlon=maxx, urcrnrlat=maxy,
resolution='h', area_thresh=100000,
projection='merc')
patches = []
#add polygons
for poly in counties.geometry:
#deal with single polygons and multipolygons
if poly.geom_type == 'Polygon':
p = PolygonPatch(poly, facecolor='blue', alpha=1)
#plt.gca().add_patch(p)
#ax.add_patch(p)
patches.append(p)
elif poly.geom_type == 'MultiPolygon':
for single in poly:
q = PolygonPatch(single,facecolor='red', alpha=1)
#ax.add_patch(p)
patches.append(q)
m.drawcoastlines(linewidth=.1)
m.fillcontinents()
m.drawcountries(linewidth=.25,linestyle='solid')
m.drawstates(linewidth=.25,linestyle='dotted')
m.drawmapboundary(fill_color='white')
ax.add_collection(mpl.collections.PatchCollection(patches, match_original=True))
ax.plot()
plt.show()
1 个回答
3
检查一下你的shapefile(形状文件)是否使用了正确的投影系统。现在Basemap(基础地图)设置的是墨卡托投影。确认这一点后,我的程序就正常运行了。