Search code examples
pythonplotlyplotly-python

How to horizontally orient a bar plot in plotly using python?


I have a bar plot that resembles this something like this-

import plotly.graph_objects as go
months = ["ABC","XYZ"]

fig = go.Figure()
fig.add_trace(go.Bar(
    x=months,
    y=[3.95,4.04],
    name='SMD',
    marker_color='yellow'
))
fig.add_trace(go.Bar(
    x=months,
    y=[3.78,4.06],
    name='Camrest',
    marker_color='black'
))
fig.add_trace(go.Bar(
    x=months,
    y=[4.16,4.28],
    name='MWOZ 2.1',
    marker_color='cadetblue'
))

fig.update_layout(barmode='group', template="plotly_white")

fig.show()

I would like to anti-clockwise rotate the bar plot by 45 degrees, that is, horizontally orient the bar graph. How can I achieve this?

Also, how can I add a custom label to the y-axis as it currently only has the number scale and no axis name?


Solution

  • A horizontal bar graph can be created by reversing the x- and y-axes of a normal bar graph and specifying the graph direction. In addition, the y-axis is reversed. Refer to this in the official reference.

    import plotly.graph_objects as go
    months = ["ABC","XYZ"]
    
    fig = go.Figure()
    fig.add_trace(go.Bar(
        y=months,
        x=[3.95,4.04],
        name='SMD',
        marker_color='yellow',
        orientation='h'
    ))
    fig.add_trace(go.Bar(
        y=months,
        x=[3.78,4.06],
        name='Camrest',
        marker_color='black',
        orientation='h'
    ))
    fig.add_trace(go.Bar(
        y=months,
        x=[4.16,4.28],
        name='MWOZ 2.1',
        marker_color='cadetblue',
        orientation='h'
    ))
    
    fig.update_layout(barmode='group', template="plotly_white", yaxis=dict(autorange='reversed'))
    
    fig.show()
    

    enter image description here