Hello, everyone!
I’m using st.plotly_chart to create a map.
The code to generate the map is this:
And it looks like this on deploy:
My question is:
Does anyone know if I can remove the st.selectbox (it shows options for all states in the country) and, instead, have the user being able to click on the map and select the state that they wish to get details on (that would be displayed in the dataframe to the left)?
Thanks!
You can use selections with st.plotly_chart: st.plotly_chart - Streamlit Docs
I confirmed using an example from Plotly’s gallery that Streamlit’s chart selections works with choropleth layers.
import streamlit as st
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
dtype={"fips": str})
import plotly.express as px
fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp',
color_continuous_scale="Viridis",
range_color=(0, 12),
scope="usa",
labels={'unemp':'unemployment rate'}
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
event = st.plotly_chart(fig, on_select="rerun", selection_mode=["points","box","lasso"])
event
2 Likes
What a nice solution, thank you so much! I’ll implement it and show the results here
It worked perfectly!
For anyone that needs to solve the same challenge, here is the code:
fig = criar_grafico_estados(df_mapa_grafico, geojson_data)
event = st.plotly_chart(fig, on_select="rerun", selection_mode=["points","box","lasso"])
points = event["selection"].get("points", [])
if points:
first_point = points[0]
sigla = first_point["properties"].get("sigla", None)
else:
sigla = None
You can also use st.write(event) to get all the data from the region and focus on what you need!
1 Like
system
Closed
October 9, 2024, 4:03pm
5
This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.