How to plot comparison in Streamlit dynamically with multiselect?
Asked Answered
F

1

0

I created a comparison app with streamlit and I want to compare it dynamically.

Here's my code that i write

import streamlit as st
import matplotlib.pyplot as plt
import pandas as pd

sampel_data={'Company':['A','B','C','D','E','F','G','H','I','J'],
             'Profit':[3,4.5,2,2.5,1.25,3,3.25,5,6,2.75]}
df_sampel=pd.DataFrame(data=sampel_data)
st.dataframe(df_sampel)
option1=st.multiselect("Choose company to compare",df_sampel)
st.write(len(option1))
fig,ax=plt.subplots()
plt.bar(option1,height=10)
st.pyplot(fig)

My problem is how to display profit because the x/horizontal part display correctly, but when display the y/vertical part, isn't displayed correctly.

Fitzpatrick answered 4/4, 2022 at 4:10 Comment(0)
R
2

Your height parameter is wrong. Have a look here https://matplotlib.org/3.5.1/api/_as_gen/matplotlib.pyplot.bar.html.

Define a dataframe based on the selected company and make that as your height.

Code

import streamlit as st
import matplotlib.pyplot as plt
import pandas as pd

sampel_data={'Company':['A','B','C','D','E','F','G','H','I','J'],
             'Profit':[3,4.5,2,2.5,1.25,3,3.25,5,6,2.75]}
df_sampel=pd.DataFrame(data=sampel_data)
st.dataframe(df_sampel)
option1=st.multiselect("Choose company to compare",df_sampel)
st.write(len(option1))

df = df_sampel.copy()
df1 = df.set_index('Company')
df1 = df1.loc[option1]  # New dataframe based on option1

fig,ax=plt.subplots()
plt.bar(x=option1, height=df1['Profit'])
st.pyplot(fig)

Sample output

enter image description here

Resolved answered 4/4, 2022 at 6:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.