Example of showing percent difference between bars in grouped bar chart?

Hello all,
When I have a grouped bar chart as shown in the example below, I would like to show the percentage delta between each of the grouped bars as a label. Could anyone point me to documentation or examples that would cover that ?

import plotly.graph_objects as go
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')
fig.show()

If I wanted this plot to look like the following, can someone provide an example please ?

looking for a response. bump

Hi @UdayGuntupalli, you can take a look at examples with annotations, see for example https://plot.ly/python/text-and-annotations/#multiple-annotations.

@Emmanuelle: In all the documented examples, the user is expected to provide an x coordinate and a y-coordinate. In the case of my example, the x-coordinate doesn’t really hold a continuous value, it is rather a nominal text value. How can I use the annotations example in this case ?

Good question! In fact, there is a mapping between a categorical axis and a continuous one, with the positions of the different categories corresponding to their indices. For example you can do

import plotly.graph_objects as go
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')
for i, animal in enumerate(animals):
    fig.add_annotation(
        go.layout.Annotation(
            x=i,
            y=5,
            text="text")
    )
fig.show()
1 Like