import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import geopandas as gpd
# activate this if running under jlab
# %matplotlib ipympl1. loading presidential averages¶
538.com - actually http://
the site is no longer online, so we use a copy of its presidential averages that is stored in data/DATA.csv
load this file into a dataframe df; make sure to
be careful about the types of the columns, in particular
date, that must be a proper timestampnotice that the first column is a leftover index, and so ensure it does not end up as a column in
df
# your code2. plotting¶
And what we want to do is to plot the average of the polls for each candidate.
In other words, you should obtain something like this - we will arbitrarily focus on the 2024 year only

# your code3. use interactivity¶
using the interactive view (if under Jupyter Lab) make sure to use %matplotlib ipympl, and zoom into the figure and retrieve
the date for the last data about Joe Biden
the date for the first data about Kamala Harris
# your answer in english - as a comment
# ...also write a line of code to compute this second date
# your code
first_harris_date = ...4. race end¶
from this part we will focus on the period after first_harris_date
how many candidates are still in the data ?
make sure to keep only the 2 most famous ones
how many data points do we have now for each of them ?
# your code5: loading shapefiles with geopandas¶
# here's the typical nickname for geopandas
import geopandas as gpdwe want to plot this data on a geographic map; first we need a definition of the various US states; this comes from the US Census Bureau (file us-states.zip), and we have a copy of it under data/
we load this shapefile into a geopandas object
gdf = gpd.read_file("data/us-states.zip")how many entries ?
# your codewhat are the various column types
as you can see, this is almost like a regular dataframe, except for the geometry column; which is a geographic entity, hence the term geo-dataframe
digression: using altair to produce a geographic viz¶
this may require an installation
of course you might have to install altair... how do you go about doing that again ?
see also on altair and its use on geographic data
import altair as alt
# this is for rendering altair charts within the notebook
alt.renderers.enable("html")RendererRegistry.enable('html')Here are a few examples of what we can do with this library
the simplest chart¶
# to show a geographic map from that geo-df
# (suboptimal, we'll improve that...)
# we could just write this and it would render
# alt.Chart(gdf).mark_geoshape()
# but we can also this more usual form
chart = (
alt.Chart(gdf)
.mark_geoshape()
)
chart.display()improving that view¶
now in terms of presentation, it is a little suboptimal, let’s improve this a bit
# we can improve by:
# (1) setting a width
# (2) using the albersUsa projection, which puts Alaska and Hawai under mainland
# this way we use space more effectively
# NOTE that in the process Alaska is artificially shrunk down
# it's actually the largest US state
(
alt.Chart(gdf)
.mark_geoshape()
.properties(width=600)
.project('albersUsa')
)using colors¶
now, the initial geo-dataframe has some numeric values, that we can use to color the map !
for example, there are AWATER and ALAND
which we can interpret as meaning area of water (as in lakes) and area of land respectively
gdf.head(2)and we can use one of these to color the different states
for that we would use encode() like so
(
alt.Chart(gdf)
.mark_geoshape()
.encode(
color="ALAND:Q", # Q stands for quantitative
)
.properties(width=600)
.project('albersUsa')
)better with a legend¶
# or if we prefer, same result essentially
# but this way we can be more descriptive
(
alt.Chart(gdf)
.mark_geoshape()
# legend
.encode(
color=alt.Color(field="ALAND", type="quantitative", title="land area")
)
# a bit narrower so the legend shows up
.properties(width=600)
.project('albersUsa')
)even better with tooltips¶
# also useful with altair, we can give a `tooltip` parameter to encode
# and this shows when your mouse hovers on a state
# NOTE: altair can only see the columns, not the index
# so as we want to show the name of the state, we need it in a regular column
# so you had made the choice to use the state as the index
# you may need to reset_index()
(
alt.Chart(gdf)
.mark_geoshape()
.encode(
color=alt.Color(field="AWATER", type="quantitative", title="water area"),
# and we can show there anything from the table
tooltip=["NAME", "ALAND"],
)
.properties(width=600)
.project('albersUsa')
)our goal: geographic rendering¶
in this following we will produce a summary map, which looks like this:
for all the states where we have data
the color depicts the ratio between, Harris’s and Trump’s average scores over time
also the tooltips allow to expose more details on the individual results

6. first map¶
for how many states do we have polls data ? which are they ?
# your codefor this data, compute a table with the state as index, and the two contestants polls (averaged)
# your codeusing what you’ve seen in the digression, and what you will gather if needed on the Internet, produce the above map
# your code7. outlining swing states¶
from the graph above, we want to outline the swing states
for example, we could come up with something like

hints
the method
pd.Series.isin()might come in handy for this stepalso you will probably need to search a bit by yourself, outside of what we’ve covered in the digression
SWING_STATES = [
'Nevada',
'Arizona',
'Wisconsin',
'Michigan',
'Pennsylvania',
'Georgia',
'North Carolina',
]# your code8. filling gaps (optional)¶
this is not very readable; instead we want to still get the missing states show up in gray,
and to keep the outlining of the swing states, i.e.

tip
this one is less obvious, and you are allowed to use an IA to find the solution !
# your code