Search code examples
pythonpandasannotationsplotlyplotly-express

Add multiple annotations at once to Plotly line chart


I want to add many annotations with an arrow to my line plot. However, I don't want to add them all manually (like I did in the code below). This will be a hell of a job and I would rather add the annotations directly from the column df['text'] (or a list from this column).

import plotly.express as px
import pandas as pd

# assign data of lists.  
data = {'x': [0, 1, 2, 3, 4, 5, 6, 7, 8], 
        'y': [0, 1, 3, 2, 4, 3, 4, 6, 5], 
        'text':["","","Annotation1","","Annotation2","","","",""]}
  
# Create DataFrame  
df = pd.DataFrame(data)

fig = px.line(df, x='x', y='y', title='I want to add annotation with the tekst column in my dataframe (instead of manually)')

fig.add_annotation(x=2, y=3,
            text="Annotation1 (added manual)",
            showarrow=True,
            arrowhead= 2)

fig.add_annotation(x=4, y=4,
            text="Annotation2 (added manual)",
            showarrow=True,
            arrowhead= 2)

fig.update_layout(showlegend=False)
fig.show()

The expected outcome looks like this (but then I want to add the annotations all at once with a list or something like that):

enter image description here

Many thanks in advance for your help.


Solution

  • I figured it out myself. See below the answer:

    import plotly.express as px
    import pandas as pd
    
    # assign data of lists.  
    data = {'x': [0, 1, 2, 3, 4, 5, 6, 7, 8], 
            'y': [0, 1, 3, 2, 4, 3, 4, 6, 5], 
            'text':["","","Annotation1","","Annotation2","","","",""]}
      
    # Create DataFrame  
    df = pd.DataFrame(data)
    
    fig = px.line(df, x='x', y='y', title='I want to add annotation with the tekst column in my dataframe (instead of manually)')
    
    arrow_list=[]
    counter=0
    for i in df['text'].tolist():
      if i != "":
        arrow=dict(x=df['x'].values[counter],y=df['y'].values[counter],xref="x",yref="y",text=i,arrowhead = 2,
                   arrowwidth=1.5,
                   arrowcolor='rgb(255,51,0)',)
        arrow_list.append(arrow)
        counter+=1
      else:
        counter+=1
    
    fig.update_layout(annotations=arrow_list)
    fig.show()