Shape positioning in categorical grouped bar chart

How can I put the shape in the categorical bar chart below in the middle of the bar specifying the number of giraffes in the SF Zoo (as shown in magenta)?

import plotly.graph_objects as go
import plotly.express as px
animals=['giraffes', 'orangutans', 'monkeys']

fig = go.Figure(data=[
    go.Bar(name='SF Zoo', x=animals, y=[20, 14, 23]),
    go.Bar(name='LA Zoo', x=animals, y=[12, 18, 29])
])

# Change the bar mode
fig.update_layout(barmode='group')

# Shape
fig.add_trace(go.Scatter(x=['giraffes', 'giraffes', 'orangutans', 'orangutans'],
                         y=[21, 25, 25, 16],
                         fill=None, mode="lines", line=dict(color='rgba(0,0,0,1)',width=2),
                         showlegend=False
                        )
             )

fig.show()

I figured that it can be done with absolute positioning. But this quite ugly:

import plotly.graph_objects as go
import plotly.express as px
animals=['giraffes', 'orangutans', 'monkeys']

fig = go.Figure(data=[
    go.Bar(name='SF Zoo', x=animals, y=[20, 14, 23]),
    go.Bar(name='LA Zoo', x=animals, y=[12, 18, 29])
])

# Change the bar mode
fig.update_layout(barmode='group')

# Shape
fig.add_trace(go.Scatter(x=['giraffes', 'giraffes', 'orangutans', 'orangutans'],
                         y=[21, 25, 25, 16],
                         fill=None, mode="lines", line=dict(color='rgba(0,0,0,1)',width=2),
                         showlegend=False
                        )
             )


# Top line
fig.add_shape(type="line",
    xref="paper", yref="paper",
    x0=0.1, y0=0.8,
    x1=0.43, y1=0.8,
    line=dict(
        color="magenta",
        width=3,
    ),
             )

# Left line
fig.add_shape(type="line",
    xref="paper", yref="paper",
    x0=0.1, y0=0.7,
    x1=0.1, y1=0.8,
    line=dict(
        color="magenta",
        width=3,
    ),
             )

# Right line
fig.add_shape(type="line",
    xref="paper", yref="paper",
    x0=0.43, y0=0.5,
    x1=0.43, y1=0.8,
    line=dict(
        color="magenta",
        width=3,
    ),
             )



fig.update_xaxes(showgrid=True, ticks="", tickson="labels")

fig.show()

Gives

@Alexboiboi and @nicolaskruchten is there not an easier way to to this?

There is not an easier way to do this at the moment, no, unfortunately. We’d welcome some help in the Plotly.js repo to make it easier though :slight_smile:

1 Like