Search code examples
pythonplotlyplotly-dashdashboardplotly-python

How do I add two separate text annotations to a single bar chart?


I have this plot -

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

fig = go.Figure([go.Bar(x=animals, y=[20, 14, 23])])
fig.show()

I want to add two different text annotations. I want to have one text annotation inside the bars that says "A", "B" and "C" and I want to have a second text annotation outside the bars that says "1", "2", "3"


Solution

  • Inner annotations are realized with bar chart codes. Outside the bar chart, the annotation function can be used, but it is easier to use the text mode for scatter plots.

    import plotly.graph_objects as go
    animals=['giraffes', 'orangutans', 'monkeys']
    
    fig = go.Figure([go.Bar(x=animals, y=[20, 14, 23], text=['A','B','C'], textposition='inside')])
    fig.add_trace(go.Scatter(mode='text', x=animals, y=[20, 14, 23], text=['1','2','3'], textposition='top center', showlegend=False))
    
    fig.update_yaxes(range=[0,25])
    fig.show()
    

    enter image description here