Search code examples
plotlybar-chartlinechartplotly-python

Plotly line and bar graph in the same figure


I tried to plot a bar chart then and a line chart in the same figure with Plotly, but somehow only the later trace is showed in the plot, and I'm not sure what went wrong.

Below is the code with Bar only

fig = go.Figure()

fig.add_trace(go.Bar(
            x=test['count'],
            y=test['pur_grp'],
            orientation='h',name='count'))

And the resulting graph is ok so far

enter image description here

When I added the line element to the figure, only the line element is showed in the figure

fig = go.Figure()

fig.add_trace(go.Bar(
            x=test['count'],
            y=test['pur_grp'],
            orientation='h',name='count'))

fig.add_trace(go.Scatter(x = test['total'],
                         y = test['pur_grp'],
                       name = 'Total'))

fig.show()

and the resulting figure enter image description here

I would also like to show the count value on the xaxis on the top since the "count" and "value" are of a different scale. After hours of searches but I'm still cannot find the suitable answers.

Thanks first for your advises.


Solution

  • Surprisingly, there is no information on multiple plots. Furthermore, I didn't see many examples of using the x-axis as two axes, so I found an example in the plotly community and applied your code to it. I did not see any data presented, so I used sample data to create it. As for the description of the code, I intentionally repositioned the x-axis ticks to overlap. It is assumed to be the 2nd x-axis.

    import pandas as pd
    import numpy as np
    
    grp = ['HAA','HAB','HAI','HAD','HAF','HAE','HAC','HAG','HAH','HAZ']
    test = pd.DataFrame({'pur_grp': grp*10, 'count':np.random.randint(100,10000,100)})
    test = test.groupby('pur_grp').sum().reset_index()
    test['total'] = np.random.randint(10000000,100000000,10)
    
    import plotly.graph_objects as go
    from plotly.subplots import make_subplots
    
    fig = make_subplots(specs=[[{"secondary_y": True}]])
    
    fig.update_layout(xaxis2= {'anchor': 'y', 'overlaying': 'x', 'side': 'top'})
    
    fig.add_trace(go.Bar(
        x=test['count'],
        y=test['pur_grp'],
        orientation='h',
        name='count',
    ),secondary_y=False)
    
    fig.add_trace(go.Scatter(
        x = test['total'],
        y = test['pur_grp'],
        name = 'Total',
    ),secondary_y=False)
    
    fig.data[1].update(xaxis='x2')
    
    fig.show()
    

    enter image description here