【问题标题】:一次向 Plotly 折线图添加多个注释
【发布时间】:2022-01-20 12:02:02
【问题描述】:

我想在我的线图中添加许多带有箭头的注释。但是,我不想手动添加它们(就像我在下面的代码中所做的那样)。这将是一项艰巨的工作,我宁愿直接从 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()

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

非常感谢您的帮助。

【问题讨论】:

    标签: python pandas annotations plotly plotly-express


    【解决方案1】:

    我自己想通了。请看下面的答案:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 2021-10-28
      • 2016-03-04
      • 1970-01-01
      相关资源
      最近更新 更多