Reputation: 1
I am trying to do charts with multiselect options using Streamlit app. Actually, I only achieve to do a chart with a unique selectbox (no multiple choices).
This is the code below that works with a unique selection:
df = pd.DataFrame(px.data.gapminder())
def plot():
clist = data['country'].unique()
country = st.selectbox('Select country', clist)
st.header('You selected:', country)
fig = px.line(df[df['country'] == country], x = "year", y = "gdpPercap", title = country)
st.plotly_chart(fig)
But when I replace st.selectbox
by st.multiselect
the plot does not work.
Upvotes: 0
Views: 4469
Reputation: 31750
You can do it like this:
import pandas as pd
import streamlit as st
import plotly.express as px
import plotly.graph_objects as go
def plot():
df = pd.DataFrame(px.data.gapminder())
clist = df["country"].unique().tolist()
countries = st.multiselect("Select country", clist)
st.header("You selected: {}".format(", ".join(countries)))
dfs = {country: df[df["country"] == country] for country in countries}
fig = go.Figure()
for country, df in dfs.items():
fig = fig.add_trace(go.Scatter(x=df["year"], y=df["gdpPercap"], name=country))
st.plotly_chart(fig)
plot()
using st.multiselect
and then add_trace
to add every country after the other. The dict
dfs
is there to map every sub-dataframe for the country for easy access.
It gives the following:
Upvotes: 1