Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a point-feature shapefile to map using cartopy

Tags:

cartopy

I have two shapefiles. One is a point feature shapefile, named "point.shp", the other is a polygon shapefile named "polygon.shp". Both I want to add to a map using cartopy. I managed to add the "polygon.shp", but failed with the "point.shp".

Here's my code:

import matplotlib.pyplot as plt
from cartopy import crs
from cartopy.io.shapereader import Reader
from cartopy.feature import ShapelyFeature

ax = plt.axes(projection=crs.PlateCarree())

# add the polygon file, worked
ax.add_geometries(Reader("polygon.shp").geometries(), crs.PlateCarree(), facecolor='w')

# or(also worked):
ax.add_feature(ShapelyFeature(Reader("polygon.shp").geometries(), crs.PlateCarree(), facecolor='r'))

# but these two ways both failed with the "point.shp"
ax.add_geometries(Reader("point.shp").geometries(), crs.PlateCarree())

# or, this doesn't work neither:
ax.add_feature(ShapelyFeature(Reader("polygon.shp").geometries(), crs.PlateCarree(), facecolor='r'))

Does any one know how to do this, or why, without retrieving all the points' x, y coords and then plotting them?

And with coordinates(x, y values), ax.plot() works, but ax.scatter() fails, why?

Thanks

like image 908
gepcel Avatar asked Aug 16 '14 13:08

gepcel


People also ask

What is Cartopy in Python?

Cartopy is a Python package designed for geospatial data processing in order to produce maps and other geospatial data analyses. Cartopy makes use of the powerful PROJ, NumPy and Shapely libraries and includes a programmatic interface built on top of Matplotlib for the creation of publication quality maps.


1 Answers

add_geometries currently turns a geometry into a polygon and then colours it appropriately, which of course means that when you pass points the add_geometries, the polygons are not visible. Potentially cartopy could do a better job of this in the future, but in the meantime, it sounds like you just want to use something like scatter to visualize your data.

You can achieve this by getting the x and y coordinate values out of the geometry and passing these straight on to scatter with the appropriate transform:

import cartopy.crs as ccrs
import cartopy.io
import matplotlib.pyplot as plt


fname = cartopy.io.shapereader.natural_earth(resolution='10m',
                                               category='cultural',
                                               name='populated_places_simple')

plt.figure(figsize=(12, 6))
ax = plt.axes(projection=ccrs.Robinson())

ax.set_title('Populated places of the world.')
ax.coastlines()

points = list(cartopy.io.shapereader.Reader(fname).geometries())

ax.scatter([point.x for point in points],
           [point.y for point in points],
           transform=ccrs.Geodetic())

plt.show()

output

HTH

like image 115
pelson Avatar answered Sep 28 '22 00:09

pelson