简体   繁体   English

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

[英]Add multiple annotations at once to Plotly line chart

I want to add many annotations with an arrow to my line plot.我想在 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).这将是一项艰巨的工作,我宁愿直接从 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()

The expected outcome looks like this (but then I want to add the annotations all at once with a list or something like that):预期的结果看起来像这样(但是我想用一个列表或类似的东西一次添加所有注释):

在此处输入图像描述

Many thanks in advance for your help.非常感谢您的帮助。

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="News",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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM