Skip to content

Instantly share code, notes, and snippets.

@fernandascovino
Last active March 13, 2023 20:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fernandascovino/c31c9303bd3ba4eb3eb6c9df09008c53 to your computer and use it in GitHub Desktop.
Save fernandascovino/c31c9303bd3ba4eb3eb6c9df09008c53 to your computer and use it in GitHub Desktop.
Make an interactive graph combining a scatter and a map in Python. The goal here is to combine both similar to: https://twitter.com/RosanaFerrero/status/1610257176978755586
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
from plotly.subplots import make_subplots
df = px.data.gapminder()
# Rewritten to show side by side
fig = make_subplots(
rows=1, cols=2, shared_yaxes=True, subplot_titles=('Scatter Plot', 'Map'),
specs=[[{"type": "xy"}, {"type": "scattergeo"}]],
)
# Create the scatter plot
fig.add_trace(
px.scatter(
df.query("year == 2007"),
x='pop',
y='lifeExp',
hover_data=['country'],
log_x=True,
size_max=3).data[0],
row=1,
col=1
)
# Create the map
fig.add_trace(px.scatter_geo(
df.query("year == 2007"),
locations="iso_alpha",
size="pop", # size of markers, "pop" is one of the columns of gapminder
hover_data=['country'],
color='lifeExp',
center={"lat": 31.9686, "lon": 99.9018},
opacity=1,
).data[0], row=1, col=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment