Skip to content

Instantly share code, notes, and snippets.

@emmanuelle
Last active November 6, 2019 02:54
Show Gist options
  • Save emmanuelle/fba6f0a2c387100ac1cc027b4b37e20a to your computer and use it in GitHub Desktop.
Save emmanuelle/fba6f0a2c387100ac1cc027b4b37e20a to your computer and use it in GitHub Desktop.
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
import plotly.express as px
gapminder = px.data.gapminder().query("year == 2007").reset_index()
app = dash.Dash(__name__)
fig_scatter = px.scatter(
gapminder, x="gdpPercap", y="lifeExp",
custom_data=["index"],
color="continent", size="pop",
hover_name="country",
log_x=True, size_max=60, height=400)
fig_scatter.update_layout(dragmode='lasso')
fig_geo = px.scatter_geo(
gapminder,
locations="iso_alpha",
color="continent", hover_name="country", size="pop",
projection="natural earth", height=400)
# ------------------ Synchronize colors between the two plots ---------------
color_dict = {}
for trace in fig_scatter.data:
continent = trace['legendgroup'].split('=')[-1]
color = trace['marker']['color']
color_dict[continent] = color
def _order_colors(fig):
for trace in fig.data:
continent = trace['legendgroup'].split('=')[-1]
trace['marker']['color'] = color_dict[continent]
return fig
# -----------------------------------------------------------------------------
app.layout = html.Div([
html.H5("Lasso select scatter points to update the map"),
dcc.Graph(
id='main-figure',
figure=fig_scatter
),
dcc.Graph(
id='other-figure',
figure = fig_geo
),
]
)
@app.callback(
Output('other-figure', 'figure'),
[Input('main-figure', 'selectedData')])
def display_selected_data(selectedData):
if selectedData:
indices = [point["customdata"][0] for point in selectedData["points"]]
df = gapminder.query("index in @indices")
fig = px.scatter_geo(df, locations="iso_alpha", color="continent",
size="pop",
projection="natural earth", height=400)
fig = _order_colors(fig)
return fig
else:
return dash.no_update
if __name__ == '__main__':
app.run_server(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment