Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- %matplotlib inline
- import matplotlib
- from matplotlib.patches import Polygon
- from matplotlib.collections import PatchCollection
- import matplotlib.pyplot as plt
- from mpl_toolkits.basemap import Basemap
- import numpy as np
- import pandas as pd
- #List of Franklin County Zip Codes
- ziplist = [43146, 43202,43201,43204,43203,43206,43205,43209,43207,43211,43002,43210,43213,43004,43212,43215,43214,
- 43217,43216,43219,43221,43220,43223,43016,43222,43224,43017,43228,43227,43230,43229,43232,43026,43231,
- 43235,43236,43268,43054,43068,43081,43085,43109,43110,43119,43125,43123,43126,43137]
- #Reding in poverty data
- df = pd.read_csv('ohio/ACS_15_5YR_S1702_with_ann.csv')
- #Removing bogus columns - Probably a better way
- df = df.drop(df.columns[6:], axis=1)
- df = df.drop(df.columns[2:5], axis=1)
- df = df.drop(df.columns[0], axis=1)
- #Renaming the keepers
- df.rename(columns={'GEO.id2': 'zipcode','HC02_EST_VC01':'Poverty_Pct'}, inplace=True)
- #Removing all rows which zipcode key is not in 'ziplist'
- df = df[df['zipcode'].isin(ziplist)]
- #Converting Pverty_Pct to float
- df['Poverty_Pct'] = df['Poverty_Pct'].astype(float)
- df.head()
- #Make map with 4 corners set in Lat/Lon w/ Mercator projection type
- m = Basemap(resolution='c', # c, l, i, h, f or None
- projection='tmerc',
- llcrnrlon = -83.26, llcrnrlat = 39.79,
- urcrnrlon = -82.76, urcrnrlat = 40.175,
- lat_0 = 40, lon_0 = -83)
- m.readshapefile('cb_2015_us_zcta510_500k','frankzips', zorder=2, color = 'none')
- #I get a blank plot. Should this happen?
- #determine header name with zipcode for matching - 'ZCTA5CE10'
- print(m.frankzips_info[1])
- #Pull shapes matched with zipcodes into dataframe convering zipcode to int.
- df_poly = pd.DataFrame({
- 'shapes': [Polygon(np.array(shape), True) for shape in m.frankzips],
- 'zipcode': [int(zipcode['ZCTA5CE10']) for zipcode in m.frankzips_info]
- })
- df_poly.head()
- #Create newframe which merges df and df_poly on zipcode w/ left merge (keeping only those that match with df zips)
- newframe = pd.merge(df, df_poly, on='zipcode', how='left')
- newframe.head()
- #Add bins to dataframe based on poverty %
- num_colors = 7
- values = newframe['Poverty_Pct']
- cmap = plt.get_cmap('Oranges')
- scheme = [cmap(i / num_colors) for i in range(num_colors)]
- bins = np.linspace(values.min(), values.max(), num_colors)
- newframe['bin'] = np.digitize(values,bins) -1
- newframe.head()
- #this is where things go to hell
- plt.clf()
- fig = plt.figure() #figsize=(22, 12)
- ax = fig.add_subplot(111, frame_on=False)
- patches = []
- colors = []
- for bin, shape in zip(newframe['bin'], newframe['shapes']):
- colors.append(scheme[bin])
- patches.append(shape)
- pc = PatchCollection(patches)
- pc.set_facecolor(colors)
- pc.set_edgecolor('black')
- ax.add_collection(pc)
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement