Search code examples
plotly

How to add line plot below heatmap with same x axis?


I am using plotly heatmap with x axis being date. Now I like to add a time line plot with same color axis of date below the heatmap such that the x axis of heatmap and line plot are aligned. How to do it? Thanks


Solution

    • create a figure to contain your traces
    • add traces from heatmap and line figures to appropriate subplot
    • align xaxis using fig.update_traces(xaxis="x")
    import plotly.express as px
    from plotly.subplots import make_subplots
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame(
        index=pd.date_range("1-jan-2022", periods=15),
        data={c: np.random.randint(1, 10, 15) for c in list("ABCD")},
    )
    
    fig = make_subplots(rows=2, cols=1)
    for t in px.imshow(df.values.T, x=df.index, y=df.columns).data:
        fig.add_trace(t, row=1, col=1)
    
    for t in px.line(df, y=df.columns).data:
        fig.add_trace(t, row=2, col=1)
    
    fig.update_traces(xaxis="x")
    fig.update_layout(
        coloraxis_colorbar={"len": 0.5, "yanchor": "bottom"},
        legend={"yanchor": "top", "y": 0.5, "tracegroupgap": 0},
    )
    

    enter image description here