Skip to content

Instantly share code, notes, and snippets.

@ljwolf
Created February 16, 2018 14:52
Show Gist options
  • Save ljwolf/01e96ad38d5ad6a25c7ed1629bca3927 to your computer and use it in GitHub Desktop.
Save ljwolf/01e96ad38d5ad6a25c7ed1629bca3927 to your computer and use it in GitHub Desktop.
small script to plot the weights from a pysal object using polygons in a geopandas dataframe
import matplotlib.pyplot as plt
import numpy as np
def plot_weights(gdf, W, indexed_on='', ax=None):
if ax is None:
f = plt.figure(figsize=(1.6*8, 8))
ax = plt.gca()
gdf.plot(linewidth=.1, color='white', ax=ax)
for idx, neighbors in W:
if idx in W.islands:
continue
if indexed_on != '':
neighbors = gdf[gdf[indexed_on].isin(neighbors)].index.tolist()
idx = gdf[gdf[indexed_on] == idx].index.tolist()[0]
centroids = gdf.ix[neighbors].geometry.apply(lambda pgon: (pgon.centroid.x, pgon.centroid.y))
centroids = np.vstack(centroids.values)
focal = np.hstack(gdf.ix[idx].geometry.centroid.xy)
for neighbor in centroids:
ax.plot(*zip(focal, neighbor), color='firebrick', linewidth=.1)
ax.set_xticks([])
ax.set_yticks([])
ax.set_title('Rook Contiguity for US Counties')
return f,ax
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment