Search code examples
python-3.xplotlystreamlit

How to display data across, by row, in pie chart in plotly/streamlit?


I have pandas df that looks like this that I want to display as a dashboard:

fname    col1      col2     col3    sum 
A         2         3         3      10
B         1         2         3      12
C         6         6         3      13

If a fname is selected by row, I want to display the pie slices as the column values by row.

What is the best way to display the data by fname grouped across by row in a pie chart?

I am not sure what to display when all the column values for fname are selected.

I tried creating a sunburst chart like so, but the chart is extremely convoluted:

 px.sunburst(df, values='sum', path=[
        'col3',
        'col2',
        'col1',
        'fname'],
        title='pie')

Solution

  • Here is a basic example.

    import plotly.express as px
    import pandas as pd
    import streamlit as st
    
    data = {
        'ctry': ['USA', 'PHI', 'CHN'],
        'gold': [12, 1, 20,],
        'silver': [4,4, 12],
        'bronze': [8, 2, 30],
        'sum': [24, 7, 62]
    }
    
    df = pd.DataFrame(data)
    st.dataframe(df)
    
    cols = st.columns([1, 1])
    
    with cols[0]:
        medal_type = st.selectbox('Medal Type', ['gold', 'silver', 'bronze'])
        
        fig = px.pie(df, values=medal_type, names='ctry',
                     title=f'number of {medal_type} medals',
                     height=300, width=200)
        fig.update_layout(margin=dict(l=20, r=20, t=30, b=0),)
        st.plotly_chart(fig, use_container_width=True)
    
    with cols[1]:
        st.text_input('sunburst', label_visibility='hidden', disabled=True)
        fig = px.sunburst(df, path=['ctry', 'gold', 'silver', 'bronze'],
                          values='sum', height=300, width=200)
        fig.update_layout(margin=dict(l=20, r=20, t=30, b=0),)
        st.plotly_chart(fig, use_container_width=True)
    

    Output

    enter image description here