import pandas as pd
import geopandas
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
voter_df = pd.read_csv('nm_voter_data.csv')
# Column data are strings -- remove commas & convert to integers
df_columns = voter_df.columns
for i in range(1, len(df_columns)):
voter_df[df_columns[i]] = voter_df[df_columns[i]].str.replace(',','').astype('int')
# Add new column to the dataframe describing the proportion of republicans
voter_df['proportion_republican'] = voter_df['Republican']/voter_df.sum(axis=1)
# Read in the shapefile data to get the NM map
counties_df = geopandas.read_file('shapefiles/tl_2010_35_county10.shp')
# Dona Ana is written differently in each dataframe, need to change one of them to match the other
counties_df.loc[19, 'NAME10'] = 'Dona Ana'
counties_df = counties_df.merge(voter_df,left_on='NAME10',right_on='County')
# Create the Choropleth plot using geopandas plot and matplotlib
fig, ax = plt.subplots(1, 1)
ax.set_title("Proportion of Republican Voters in New Mexico Counties (2010)")
divider = make_axes_locatable(ax)
cax = divider.append_axes("bottom", size="5%", pad=0.05)
ax.set_axis_off()
counties_df.plot(column='proportion_republican', cmap='RdBu_r',edgecolor='white', ax=ax, legend=True, legend_kwds={'orientation':'horizontal'}, cax=cax)
<Axes: title={'center': 'Proportion of Republican Voters in New Mexico Counties (2010)'}>