Search code examples
pythonplotly

Combined xaxis and header of table with plotly Python


I would like to do something quite similar to the picture with plotly on python. I tried to find a way with subplots and shared_axis but no way to find a correct way. Is it possible to share the x axis of a bar chart with the column titles of a table?

graph bar with shared xaxis graph bar with shared xaxis


Solution

    • this can be simulated with two traces
    • first trace is a standard bar chart, with yaxis domain constrained to 80% of the figure
    • second trace is a bar showing values as text and a fixed height against a second yaxis. yaxis2 is constrained to 10% of the domain
    import plotly.express as px
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({"year": range(2011, 2022)}).assign(
        pct=lambda d: np.random.uniform(-0.08, 0.08, len(d))
    )
    
    px.bar(df, x="year", y="pct").add_traces(
        px.bar(df, x="year", y=np.full(len(df), 1), text="pct")
        .update_traces(
            yaxis="y2",
            marker={"line": {"color": "black", "width": 1.5}, "color": "#E5ECF6"},
            texttemplate="%{text:,.2%}",
        )
        .data
    ).update_layout(
        yaxis={"domain": [0.2, 1], "tickformat": ",.2%"},
        yaxis2={"domain": [0, 0.1], "visible": False},
        xaxis={"title": "", "dtick": 1},
    )
    

    enter image description here