In [8]:
import numpy as np
import pandas as pd
import geopandas as gdf
import matplotlib.pyplot as plt
import matplotlib.colors as clt
In [5]:
shapvalues = pd.read_pickle("data/shapvalues.p")
clusters = pd.read_pickle("data/clusters.p")
explained = pd.read_pickle("data/explained.p")
election = pd.read_pickle("data/election.p")
centroids = pd.read_pickle("data/centroids.p") # gisjoin
state_names = pd.read_pickle("data/state_names.p")
varnames = pd.read_pickle("data/varnames.p")
In [19]:
counties = pd.read_pickle("data/counties.p")
states = pd.read_pickle("data/states.p")
In [9]:
def chorophlet(gdf,serie,states,ax=None,map_kws=None,ticks=None):
    ct = gdf.join(serie)
    column = serie.name
    ax = ax or plt.gca()
    #legend_kwds = dict(ticks=ticks,shrink=0.5)
    #legend_kwds = {"loc":"lower right"}
    #ct.plot(column=column,ax=ax,legend=True,legend_kwds=legend_kwds, **map_kws)
    ct.plot(column=column,ax=ax,legend=False, **map_kws)
    states.plot(facecolor="none", edgecolor="#222222",linewidth=0.3,ax=ax)

    ax.set_xlim(-2500000,2300000)
    ax.set_ylim(-1500000,1800000)
    ax.axis('off')

    ax_alaska = ax.inset_axes([0,0,0.3,0.3])
    ct.plot(column=column,ax=ax_alaska,**map_kws)
    ax_alaska.set_xlim(-4000000,-2200000)
    ax_alaska.set_ylim(2200000,4600000)
    ax_alaska.axis('off')
#    
    ax_havaii = ax.inset_axes([0.3,0.01,0.1,0.15])
    ax_havaii.axis('off')
    ct.plot(column=column,ax=ax_havaii,**map_kws)
    ax_havaii.set_xlim(-6300000,-5900000)
    ax_havaii.set_ylim(-80000,500000)
In [21]:
colors = ["#660000","#aa0000","#dd6600","#cc99dd","#0000aa","#3366dd","#004466","#bb3366","#bb3300","#995533"] # interpreted colors
colormap = clt.LinearSegmentedColormap.from_list("colors",colors=colors)

Waterfall Trump¶

Both waterfall are created as a list of arrows ordered from these of least importance to these with highest importance. Lot of code contains data-frame operation to select and order subser of the data. Upper part contains a chorophlet map for each cluster.

In [25]:
Trump = [0,1,2,7,8,9] 
fig,axes=plt.subplots(ncols=6,nrows=2,figsize=(24,16),gridspec_kw={'height_ratios':[1,5],'hspace':0.02})

basex = 31.8
yticks=True
for exemplar,ax in zip(Trump,axes[1:].flatten()):
    gisindex = centroids[exemplar]
    arrowlengths=shapvalues.loc[gisindex]*100
    countyname = counties.loc[gisindex].NAME
    state = counties.loc[gisindex].STATEFP
    name = "{} Ct. ({})".format(countyname,state_names.loc[state].state)
    x = basex
    for y,length in enumerate(arrowlengths):
        color = '#db1100' if length > 0 else '#000ca8'
        hl = 5 if abs(length) > 5 else 1
        ax.arrow(x,y,length,0,
                 head_width = 0.7,head_length=hl,width=0.7,
                 fc=color,ec=color,length_includes_head=True)
        x += length
    ax.set_xlabel(name)
    ax.axvline(basex,ls=':',lw=0.6,c="#333333")
    ax.axvline(x,ls='--',lw=1,c="#333333",zorder=-10)
    ax.set_yticks(range(len(arrowlengths)))
    ax.set_xlim(-55,55)
    ax.set_ylim(-1,26)
    ax.grid(axis="y",lw=0.6,c="#999999",ls=":")
    ax.arrow(basex,y+1,x-basex,0,fc=colors[exemplar],ec=colors[exemplar],width=.8,head_width = 0.8,head_length=10,length_includes_head=True)
    
    if yticks:
        ax.set_yticklabels(varnames.loc[arrowlengths.index].colname.values)
    else:
            ax.set_yticklabels([])
    yticks=False

for exemplar,ax in zip(Trump,axes[0:].flatten()):
    selcolors = [colors[i] if i==exemplar else '#FFFFFF' for i in range(10)]
    selmap = clt.LinearSegmentedColormap.from_list("sel",colors=selcolors)
    map_kws_cat = dict(cmap=selmap,edgecolor="gray",linewidth=0)
    chorophlet(counties,clusters,states,ax=ax,map_kws=map_kws_cat)
No description has been provided for this image

Waterfall Clinton¶

In [26]:
Clinton = [4,5,6,3]
fig,axes=plt.subplots(ncols=4,nrows=2,figsize=(20,16),gridspec_kw={'height_ratios':[1,5],'hspace':0.02})

pos1 = axes[1,3].get_position() # get the original position 
shift = 0.02
pos2 = [pos1.x0 + shift, pos1.y0,  pos1.width, pos1.height]
axes[1,3].set_position(pos2)
pos1 = axes[0,3].get_position() # get the original position 
shift = 0.02
pos2 = [pos1.x0 + shift, pos1.y0,  pos1.width, pos1.height]
axes[0,3].set_position(pos2)

basex = 31.8
yticks=True
for exemplar,ax in zip(Clinton,axes[1:].flatten()):
    gisindex = centroids[exemplar]
    arrowlengths=shapvalues.loc[gisindex]*100
    countyname = counties.loc[gisindex].NAME
    state = counties.loc[gisindex].STATEFP
    name = "{} Ct. ({})".format(countyname,state_names.loc[state].state)
    print(name)
    x = basex
    for y,length in enumerate(arrowlengths):
        color = '#db1100' if length > 0 else '#000ca8'
        hl = 5 if abs(length) > 5 else 1
        ax.arrow(x,y,length,0,
                 head_width = 0.7,head_length=hl,width=0.7,
                 fc=color,ec=color,length_includes_head=True)
        x += length
    ax.set_xlabel(name)
    ax.axvline(basex,ls=':',lw=0.6,c="#333333")
    ax.axvline(x,ls='--',lw=0.6,c="#333333",zorder=-10)
    ax.set_yticks(range(len(arrowlengths)))
    ax.set_xlim(-55,55)
    ax.set_ylim(-1,26)
    ax.grid(axis="y",lw=0.6,c="#999999",ls=":")
    
    ax.arrow(basex,y+1,x-basex,0,fc=colors[exemplar],ec=colors[exemplar],width=.8,head_width = 0.8,head_length=10,length_includes_head=True)
    if yticks:
        ax.set_yticklabels(varnames.loc[arrowlengths.index].colname.values)
    else:
            ax.set_yticklabels([])
    yticks=False

for exemplar,ax in zip(Clinton,axes[0:].flatten()):
    selcolors = [colors[i] if i==exemplar else '#FFFFFF' for i in range(10)]
    selmap = clt.LinearSegmentedColormap.from_list("sel",colors=selcolors)
    map_kws_cat = dict(cmap=selmap,edgecolor="gray",linewidth=0)
    chorophlet(counties,clusters,states,ax=ax,map_kws=map_kws_cat)
Ramsey Ct. (Minnesota)
Hoke Ct. (North Carolina)
Sioux Ct. (North Dakota)
Kent Ct. (Maryland)
No description has been provided for this image