Skip to content

Instantly share code, notes, and snippets.

@eliasdabbas
Last active November 6, 2024 12:07
Show Gist options
  • Save eliasdabbas/738cd6931dea0a7206c9b602705ae103 to your computer and use it in GitHub Desktop.
Save eliasdabbas/738cd6931dea0a7206c9b602705ae103 to your computer and use it in GitHub Desktop.
Create a cartogram by assigning size to flags (or two letter symbols) without displaying map lines
import plotly.express as px
import adviz
import numpy as np
import pandas as pd
population = pd.read_html('https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population')
pop = population[0][['Location', 'Population']].copy()
flags = []
for country in pop['Location']:
try:
flags.append(adviz.flag(country))
except Exception:
if country == 'Palestine':
flags.append(adviz.flag("PS"))
elif country == 'Russia':
flags.append(adviz.flag("RU"))
elif country == 'United States':
flags.append(adviz.flag("US"))
elif country == 'United Kingdom':
flags.append(adviz.flag("GB"))
elif country == 'Iran':
flags.append(adviz.flag("IR"))
elif country == 'Czech Republic':
flags.append(adviz.flag("CZ"))
else:
flags.append(None)
continue
pop['flag'] = flags
pop = pop.dropna(subset=['flag'])
population[0][population[0]['Location'].str.contains('Czech')]
fig = px.scatter_geo(
pop,
locations='Location',
locationmode='country names',
text='flag',
size='Population',
hover_name='Location',
title='Population',
height=700,
opacity=0,
)
fig.layout.geo.showframe = False
fig.layout.geo.lataxis.range = [-53, 76]
fig.layout.geo.lonaxis.range = [-125, 171.5]
fig.layout.geo.landcolor = 'white'
fig.layout.geo.showcountries = False
fig.layout.geo.coastlinecolor = 'white'
fig.data[0].textfont.size = np.sqrt(pop['Population']).div(300).add(1).round()
fig.data[0].marker.color = 'white'
fig
# Example for plotting US states, with marker size corresponding to the satate's GDP
states_gdp = pd.read_html('https://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_GDP')
states = states_gdp[0].iloc[:, [0, 2]].head(50).copy()
states.columns = ['state', 'gdp']
states['state'] = states['state'].str.replace(r' \*', '', regex=True)
states.head()
state_abbrev = pd.read_html('https://en.wikipedia.org/wiki/List_of_U.S._state_and_territory_abbreviations')
abbrev = state_abbrev[1].iloc[:, [0, 5]]
abbrev.columns = ['state', 'code']
abbrev.dropna().head()
state_gdp = pd.merge(states, abbrev)
state_gdp['gdp'] = state_gdp['gdp'].mul(1_000_000)
state_gdp.head()
fig = px.scatter_geo(
state_gdp,
locations='code',
locationmode='USA-states',
text='code',
size='gdp',
hover_name='state',
scope='usa',
color='gdp',
height=700,
title='GDP by state',
color_continuous_scale='cividis',
opacity=0,
)
fig.layout.geo.landcolor = 'white'
fig.layout.geo.showcountries = False
fig.layout.geo.countrycolor = 'white'
fig.layout.geo.coastlinecolor = 'white'
fig.data[0].textfont.size = np.sqrt(state_gdp['gdp']).div(32000).round()
fig.layout.coloraxis.showscale = False
fig.layout.title.x = 0.5
fig.data[0].hovertemplate = '<b>%{hovertext}</b><br>GDP: $%{marker.color:,}'
fig.layout.title.subtitle.text = 'California > Texas > New York'
fig
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment