Skip to content

Instantly share code, notes, and snippets.

@timothyrenner
Last active February 25, 2018 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timothyrenner/a9e834d4e51af056844decbe16b1953b to your computer and use it in GitHub Desktop.
Save timothyrenner/a9e834d4e51af056844decbe16b1953b to your computer and use it in GitHub Desktop.
Building a map of haunted places using shapefiles and cartopy.
import pandas as pd
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import cartopy.io.shapereader as shpreader
from shapely.ops import cascaded_union
non_conus_states = {'VI', 'AK', 'HI', 'PR', 'GU', 'MP', 'AS'}
# Read in the USA data.
usa_reader = shpreader.Reader('data/cb_2016_us_state_500k.shp')
states = [
state for state in usa_reader.records()
if state.attributes['STUSPS'] not in non_conus_states
]
# Obtain the bounds for the plot.
usa_bounds = cascaded_union(
[state.geometry.envelope.buffer(0.5) for state in states]
).bounds
# Merge the USA into a single polygon.
usa = cascaded_union(
# Shrink the states just a tad to draw the edges around the states.
[state.geometry.buffer(-2e-2) for state in states]
)
# Read in the haunted places and isolate the places in the
# bounding box of the USA polygon. This is a cheap way to
# take out some of the more obvious outliers.
haunted_places = \
pd.read_csv('data/haunted_places.csv')\
.query(
"(longitude > @usa.bounds[0]) and "
"(longitude < @usa_bounds[2]) and "
"(latitude > @usa.bounds[1]) and "
"(latitude < @usa.bounds[3])"
)
# Prepare a cartopy projection for the plot.
proj = ccrs.AlbersEqualArea(
central_longitude=-98,
central_latitude=39.5
)
fig = plt.figure(figsize=(16,16))
ax = plt.axes(projection=proj)
ax.add_feature(
cfeature.ShapelyFeature(usa, ccrs.PlateCarree()),
facecolor="black"
)
ax.plot(
haunted_places.longitude,
haunted_places.latitude,
"o",
markerfacecolor="white",
markeredgecolor="#1cff2b",
markeredgewidth=0.2,
markersize=1.05,
transform=ccrs.PlateCarree()
)
ax.set_extent([
usa_bounds[0],
usa_bounds[2],
usa_bounds[1],
usa_bounds[3]
], ccrs.PlateCarree())
ax.set_title("Haunted Places of America", fontdict={"fontsize": 18})
# This makes the background of the map transparent.
ax.outline_patch.set_visible(False)
ax.background_patch.set_visible(False)
fig.savefig('haunted_places_map.png', transparent=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment