Skip to content

Instantly share code, notes, and snippets.

@ben-n93
Last active March 3, 2023 11:28
Show Gist options
  • Save ben-n93/35b84a4605645b09d4248219c5200970 to your computer and use it in GitHub Desktop.
Save ben-n93/35b84a4605645b09d4248219c5200970 to your computer and use it in GitHub Desktop.
import folium
import pandas as pd
# Cleaning the data.
df = pd.read_csv("../data/horror_films.csv")
df.drop_duplicates(inplace=True)
table = pd.pivot_table(data=df,index='Setting', values='Film', aggfunc='count')
table.to_csv("../data/cleaned_horror_films.csv")
# Creating the map.
m = folium.Map(location=[40, -95],zoom_start=4)
STATE_GEO = "../data/us_states.json"
DATA_CSV = "../data/cleaned_horror_films.csv"
DATA_CSV_PD = pd.read_csv(DATA_CSV)
# Layers.
layer = folium.Choropleth(
geo_data=STATE_GEO,
name="1960-2022",
data=DATA_CSV_PD,
columns=["Setting", "Film"],
key_on="feature.id",
fill_color="Reds",
fill_opacity=0.7,
line_opacity=.1,
nan_fill_color="white",
highlight='True',
legend_name="Number of horror films per state",
).add_to(m)
# Set tooltip.
df_indexed = DATA_CSV_PD.set_index('Setting')
for s in layer.geojson.data['features']:
try:
s['properties']['Films set in state'] = int(df_indexed.loc[s['id'], 'Film'])
except KeyError:
s['properties']['Films set in state'] = 0
folium.GeoJsonTooltip(['name', 'Films set in state']).add_to(layer.geojson)
# Save map.
m.save("../us_horror_films_v2.html")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment