一次向 Plotly 折线图添加多个注释

Add multiple annotations at once to Plotly line chart

我想在我的线图中添加许多带箭头的注释。但是,我不想手动添加它们(就像我在下面的代码中所做的那样)。这将是一项艰巨的工作,我宁愿直接从 df['text'] 列(或来自该列的列表)添加注释。

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()

预期的结果是这样的(但我想用列表或类似的东西一次添加注释):

非常感谢您的帮助。

我自己想出来了。看下面的答案:

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()