Search code examples
javascriptplotlyplotly.js

Regroup low% data in a pie chart


I'm struggling to find a way to group low percentage data in a specific section, for example "Others" (let's say below 1%) in a pie chart in a dynamic way (i.e. when I uncheck a data in the legend, the chart is updated automatically, so some data go back above the 1% and are not part of the others anymore.) I work with this kind of data, and as you can see, it is not very readable and not very aesthetic:

Pie Chart with not grouped data

But I would like something like

Pie Chart with grouped data

I already got something similar, but this was not dynamic because I was working on the data before giving it to the graph

Thanks for any answers


Solution

    • I didn't see javascript tag before working on this...
    • simple approach - just prepare your data to aggregate the small slices before using plotly
    from plotly.subplots import make_subplots
    import plotly.graph_objects as go
    import plotly.express as px
    import numpy as np
    
    # generate some data...
    df = pd.DataFrame({"percent": np.concatenate([np.random.uniform(80, 100, 5), np.random.uniform(2, 20, 20)])})
    df["percent"] = df["percent"] / df["percent"].sum()
    
    # just plot as a pie,
    fig = px.pie(df, values="percent")
    
    
    # let's merge the small slices in the data,  plot is the same
    df2 = pd.concat([df.loc[df["percent"] < 0.02].sum().to_frame().T, df.loc[df["percent"] >= 0.02]])
    fig2 = px.pie(df2, values="percent")
    
    
    figsp = make_subplots(
        rows=1,
        cols=2,
        specs=[[{"type": "pie"}, {"type": "pie"}]],
        subplot_titles=["ungrouped", "grouped"],
    )
    figsp.add_trace(fig.data[0], row=1, col=1).add_trace(fig2.data[0], row=1, col=2)
    

    enter image description here