Search code examples
plotlyfacetplotly-python

Use bar chart and average line on facet grid in Plotly


I want to plot facet grid with barcharts and average line for each facet. Example of desired result of one graph can be seen on the image here but the final figure should have multiple graphs like that, each in a facet.

I have tried the solution from this question, but I didn't find a way to use it with facets. I'd like to use facet_col option as it draws as many plots as distinct values in the column.

Ideally, I want to have these two figures displayed on one (the code below is not syntactically correct, just to give understanding).

px.bar(df, x='category', y='user_count',facet_col='domain', facet_col_wrap=4)
px.line(df, x='category', y='user_count_avg',facet_col='domain', facet_col_wrap=4)

Solution

    • you have not provided sample data, hence have generated
    • concept: the number of facets in both figures are the same as they are created with same data frame (have same domain and category for xaxes and facets). With this in mind the same axes will have been assigned by plotly express to both figures
    • now just append lines to bars and have your required integrated figure
    import pandas as pd
    import plotly.express as px
    import numpy as np
    
    df = pd.DataFrame(
        {
            "category": np.tile(list("ABCDEF"), 6),
            "domain": np.repeat([".co.uk", ".com", ".sg", ".media", ".fr", ".de"], 6),
            "user_count": np.random.randint(20, 100, 36),
        }
    )
    df = df.groupby("domain", as_index=False).apply(
        lambda d: d.assign(user_count_avg=d["user_count"].mean())
    )
    
    b = px.bar(df, x="category", y="user_count", facet_col="domain", facet_col_wrap=4)
    l = px.line(
        df, x="category", y="user_count_avg", facet_col="domain", facet_col_wrap=4
    ).update_traces(line_color="red")
    
    b.add_traces(l.data)
    

    enter image description here