<jupyter_start><jupyter_text>change dir to resources folder<jupyter_code>os.chdir(r'Resources')
print(os.getcwd())<jupyter_output>C:\Users\wendi\My Drive\project\Resources<jupyter_text>read mask coverage data by State by county<jupyter_code>df = pd.read_csv(r'mandates_by_county.csv')

df<jupyter_output><empty_output><jupyter_text>geocode county for gmaps<jupyter_code># ONLY RUN ONCE FOR GEOCODING data
def geocode_county():
    url = f'http://api.positionstack.com/v1/forward?access_key={geo_key}&query={{}}'

    with open(r'mandates_by_county_geocode.csv', 'w') as fw:
        print(f'state,county,lat,lon,statefips,countyfips,maskdays,days,maskcoverage', file=fw)

        for index, row in df.iterrows():
        #     print(index, list(row))
            state = row[0]
            county = row[1].replace(' ', '%20')
            ctyst = f'{county},%20{state}'

            url1 = url.format(ctyst)
        #     print(url1)
            r = requests.get(url1)
            dicy = r.json()
        #     pprint(dicy)

            lat = dicy['data'][0]['latitude']
            lon = dicy['data'][0]['longitude']

            df.loc[index, 'lat'] = lat
            df.loc[index, 'lon'] = lon

            print(f'{row[0]}, {row[1]}, {lat}, {lon}, {row[2]}, {row[3]}, {row[4]}, {row[5]}, {row[6]}', file=fw)
            print(f'{row[0]}, {row[1]}, {lat}, {lon}, {row[2]}, {row[3]}, {row[4]}, {row[5]}, {row[6]}')

            
# geocode_county()<jupyter_output><empty_output><jupyter_text>read from stored output<jupyter_code>df = pd.read_csv(r'mandates_by_county_geocode.csv')

df<jupyter_output><empty_output><jupyter_text>plot heatmap of mask mandates over period<jupyter_code>gmaps.configure(api_key=vacation_key)

locs = df[['lat', 'lon']]
maskdays = df['maskdays'] 

fig = gmaps.figure()

# add heat layer and set max intensity to max mask days
heat = gmaps.heatmap_layer(locs, weights=maskdays, dissipating=False, max_intensity=maskdays.max(), point_radius = 0.6)
fig.add_layer(heat)

fig<jupyter_output><empty_output><jupyter_text>merge mask mandates and presidential votes return data format columns and for merge<jupyter_code>df['statefips'] = df['statefips'].map('{:0>2d}'.format)
df['countyfips'] = df['countyfips'].map('{:0>3d}'.format)
df['countyfips'] = df['statefips'] + df['countyfips']

df = df.drop(columns='statefips')
df['county'] =  df['county'].map(lambda x: x.upper())
                                 
df<jupyter_output><empty_output><jupyter_text>read elections return data by county by year<jupyter_code>df1 = pd.read_csv(r'countypres_2000-2020.csv')

df1<jupyter_output><empty_output><jupyter_text>select time frame before covid and after covid for comparison<jupyter_code>df1 = df1[df1['year'] > 2015]

df1<jupyter_output><empty_output><jupyter_text>get only democrat and repub rows<jupyter_code>df1 = df1[df1['party'] != 'OTHER'].reset_index(drop=True)

df1<jupyter_output><empty_output><jupyter_text>pick out relevant cols and rename<jupyter_code>df2 = df1[['year', 'state_po', 'county_name', 'county_fips', 'party', 'candidatevotes', 'totalvotes']]
df2.columns = ['year', 'state', 'county', 'countyfips', 'party', 'votes', 'totvotes']

df2<jupyter_output><empty_output><jupyter_text>drop na rows<jupyter_code>df2 = df2.dropna().reset_index(drop=True)

df2<jupyter_output><empty_output><jupyter_text>create proportion of votes var<jupyter_code>df2['voteperc'] = df2['votes'] / df2['totvotes']

df2<jupyter_output><empty_output><jupyter_text>format all columns<jupyter_code>df2['countyfips'] = df2['countyfips'].map(int).map('{:0>5d}'.format)

df2<jupyter_output><empty_output><jupyter_text>merge mask mandates and presidential votes data then drop dup cols<jupyter_code>df3 = df2.merge(df, how='inner', on=['state', 'countyfips'], suffixes=('','_y'))
df3 = df3.drop(columns='county_y')

df3<jupyter_output><empty_output><jupyter_text>Combine dem and rep rows into by State by county separate into two dfs<jupyter_code>dfd = df3[df3['party'] == 'DEMOCRAT'].reset_index(drop=True)
dfr = df3[df3['party'] == 'REPUBLICAN'].reset_index(drop=True)<jupyter_output><empty_output><jupyter_text>combine dfs in by State by county<jupyter_code>dfnew = dfd.merge(dfr, left_index=True, right_index=True, suffixes=('','_r'))
dfnew['dmargin'] = dfnew['voteperc'] - dfnew['voteperc_r']

dfnew<jupyter_output><empty_output><jupyter_text>plot dem party heatmap since 2016<jupyter_code># Democrat
dfd2020 = dfnew[dfnew['dmargin'] > 0]

gmaps.configure(api_key=vacation_key)

locs = dfd2020[['lat', 'lon']]
dmargin = dfd2020['dmargin'] * 100

fig = gmaps.figure()

# add heat layer and set max intensity to max mask days
heat = gmaps.heatmap_layer(locs, weights=dmargin, dissipating=False, max_intensity=dmargin.max(), point_radius = 1)
fig.add_layer(heat)

fig<jupyter_output><empty_output><jupyter_text>plot rep party heatmap since 2016<jupyter_code>#REPUBLICAN
dfd2016 = dfnew[dfnew['dmargin'] < 0]

gmaps.configure(api_key=vacation_key)

locs = dfd2016[['lat', 'lon']]
dmargin = dfd2016['dmargin'] * 100 * - 1

fig = gmaps.figure()

# add heat layer and set max intensity to max mask days
heat = gmaps.heatmap_layer(locs, weights=dmargin, dissipating=False, max_intensity=dmargin.max() * 4, point_radius = 1)
fig.add_layer(heat)

fig<jupyter_output><empty_output><jupyter_text>regress to uncover relationship between political alignment and mask mandates<jupyter_code>dfnew<jupyter_output><empty_output><jupyter_text>define regression function to be reused<jupyter_code>def reg_plot(x_l, y_l):
    x = np.array(x_l)
    y = np.array(y_l)

    m, b = np.polyfit(x, y, 1)
    plt.plot(x, m * x + b, color='#000000', linewidth ='3', label = '{:.2f} * x + {:.2f}'.format(m, b))
    plt.legend()
    
    return m, b<jupyter_output><empty_output><jupyter_text>create data and fig variables<jupyter_code>color = ['#043070', '#700804']

x = dfnew['dmargin'] * 100
y = dfnew['maskcoverage'] * 100
xy = zip(x, y)

dem = {}
rep = {}
for percvote, percmask in xy:
    if percvote >= 0:
        dem[percvote] = percmask
    else:
        rep[percvote] = percmask<jupyter_output><empty_output><jupyter_text>plot mask mandates against politcal alignment since 2016<jupyter_code>plt.scatter(dem.keys(), dem.values(), c=color[0])
plt.scatter(rep.keys(), rep.values(), c=color[1])

plt.title('Mask Mandate over COVID-19 against Political Alignment since 2016')
plt.xlabel('Net Democratic Votes Margin (%)')
plt.ylabel('Mask Mandates over Period (%)')
plt.xlim(-100,100)
plt.ylim(0,100)

corr = reg_plot(x, y)

plt.savefig('..\Images\mandates_votes_overall.png', dpi=200)
plt.show()<jupyter_output><empty_output><jupyter_text>separate data into 2016 and 2020<jupyter_code>dfnew2020 = dfnew[dfnew['year'] == 2020]
dfnew2016 = dfnew[dfnew['year'] == 2016]<jupyter_output><empty_output><jupyter_text>plot mask mandates against 2020 political alignment<jupyter_code>x = dfnew2020['dmargin'] * 100
y = dfnew2020['maskcoverage'] * 100
xy = zip(x, y)

dem = {}
rep = {}
for percvote, percmask in xy:
    if percvote >= 0:
        dem[percvote] = percmask
    else:
        rep[percvote] = percmask
plt.scatter(dem.keys(), dem.values(), c=color[0])
plt.scatter(rep.keys(), rep.values(), c=color[1])

plt.title('Mask Mandate over COVID-19 against Political Alignment in 2020')
plt.xlabel('Net Democratic Votes Margin (%)')
plt.ylabel('Mask Mandates over Period (%)')
plt.xlim(-100,100)
plt.ylim(0,100)

corr = reg_plot(x, y)

plt.savefig('..\Images\mandates_votes_2020.png', dpi=200)
plt.show()<jupyter_output><empty_output><jupyter_text>plot mask mandates against 2016 political alignment<jupyter_code>x = dfnew2016['dmargin'] * 100
y = dfnew2016['maskcoverage'] * 100
xy = zip(x, y)

dem = {}
rep = {}
for percvote, percmask in xy:
    if percvote >= 0:
        dem[percvote] = percmask
    else:
        rep[percvote] = percmask
plt.scatter(dem.keys(), dem.values(), c=color[0])
plt.scatter(rep.keys(), rep.values(), c=color[1])

plt.title('Mask Mandate over COVID-19 against Political Alignment in 2016')
plt.xlabel('Net Democratic Votes Margin (%)')
plt.ylabel('Mask Mandates over Period (%)')
plt.xlim(-100,100)
plt.ylim(0,100)

corr = reg_plot(x, y)

plt.savefig('..\Images\mandates_votes_2016.png', dpi=200)
plt.show()<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup