Created
May 21, 2024 15:14
-
-
Save cpsievert/694a3da1ad8b71641019af0c2198e9a0 to your computer and use it in GitHub Desktop.
Access click on plotly choroplethmapbox
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example adapted from https://plotly.com/python/mapbox-county-choropleth/ | |
import json | |
from urllib.request import urlopen | |
import pandas as pd | |
import plotly.express as px | |
import plotly.graph_objects as go | |
from shinywidgets import render_plotly | |
from shiny import reactive | |
from shiny.express import render | |
with urlopen( | |
"https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json" | |
) as response: | |
counties = json.load(response) | |
df = pd.read_csv( | |
"https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv", | |
dtype={"fips": str}, | |
) | |
@render_plotly | |
def plot1(): | |
fig = px.choropleth_mapbox( | |
df, | |
geojson=counties, | |
locations="fips", | |
color="unemp", | |
color_continuous_scale="Viridis", | |
range_color=(0, 12), | |
mapbox_style="carto-positron", | |
zoom=3, | |
center={"lat": 37.0902, "lon": -95.7129}, | |
opacity=0.5, | |
labels={"unemp": "unemployment rate"}, | |
) | |
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) | |
# Need to create a FigureWidget() for on_click to work | |
w = go.FigureWidget(fig.data, fig.layout) | |
w.data[0].on_click(on_choropleth_click) | |
return w | |
# Capture the clicked point in a reactive value | |
pt_reactive = reactive.value() | |
def on_choropleth_click(trace, points, state): | |
pt_reactive.set(points) | |
# Display the clicked point | |
@render.code | |
def click_info(): | |
return str(pt_reactive.get()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment