Search code examples
pythonplotly

How to create a plotly bar and line chart combined?


I am using

fig = px.line(df, x='date', y='var1')
fig.show()

But I want to add

fig = px.bar(df, x='date', y='var2')
fig.show()

enter image description here

How would I achieve the output illustrated on the img?


Solution

  • I think you should use fig.add_trace in this case.Please refer below code:

    import pandas as pd
    import plotly.graph_objects as go
    
    df = pd.DataFrame({
        'date': ['2022-01-07','2022-02-07','2022-03-07','2022-04-07','2022-05-07','2022-06-07','2022-07-07','2022-08-07'],
        'var1': [5,7,2,4,6,8,10,9],
        'var2': [6,7,8,5,2,6,3,1],
        'var3':[8,5,6,2,8,3,5,4],
        'var4':[7,9,7,5,3,4,2,1]})
    
    fig = go.Figure()
    fig.add_trace(go.Bar(x=df['date'],y=df['var1']))
    fig.add_trace(go.Scatter(x=df['date'],y=df['var2'],mode='lines'))
    fig.show()
    

    And here is the Output: enter image description here