【问题标题】:Annotate plotly candlestick chart with multiple arrows based on cell values in Dataframe根据 Dataframe 中的单元格值用多个箭头注释绘图烛台图
【发布时间】:2021-02-07 06:37:46
【问题描述】:

我有一个 Dataframe(我们称之为“df”),如下所示,用于使用 plotly 绘制烛台图:

         Date  Open  ...  Close                                   Headline
0  2020-10-23   190  ...    195  As Shares Tread Water Wait for a Pullback
1  2020-10-24   187  ...    177                    Why You Should Buy AAPL

在上面的 Dataframe 中,如果没有 Headline 数据,即“na”,我通过使用添加了一个默认值“No News”:

df['Headline'].fillna('No News', inplace=True)

为了将 Dataframe 绘制成烛台图,我使用了以下方法:

fig = go.Figure(data=[go.Candlestick(......

我使用了“hovertext”参数,因此当用户将鼠标悬停在特定烛台上时,您可以看到该特定日期的“标题”:

hovertext= df['Headline'] 

现在,我还想要用 箭头 和显示“新闻”的 文本 注释此烛台,以突出显示有此特定蜡烛的标题,因此用户无需悬停鼠标即可查看是否有标题(只需找出特定标题是什么)。 x 引用将是“日期”,而 y 引用可能会使用“高”。

我想我需要代码循环遍历每个标题并在烛台上注释 News!="No News"。如果 News=="No News",那么我不想在该特定实例中添加注释。

据我了解,基于此answer,注释接受列表,每个箭头的参数都是字典。所以,我使用了一个 for 循环来创建一个箭头字典列表,然后使用 fig.update_layout(annotations = list) 来绘制多个箭头。但是,这似乎不起作用(除非我误解了):

arrow_list=[]
counter=0
for i in df['Headline'].tolist():
       if i !="No News":
            arrow=dict(x=df['Headline'].values[counter],y=df['high'].values[counter],xref="x",yref="y",text="News",ax=20,ay=-30,arrowhead = 3,
                arrowwidth=1.5,
                arrowcolor='rgb(255,51,0)',)
            arrow_list.append(arrow)
            counter+=1
        else:
            counter+=1
fig.update_layout(title=f"{ticker} Stock Price for the past {days} day(s)",yaxis_title=f'{ticker} Price',
                    xaxis_title='Date',yaxis=dict(autorange=True, fixedrange=False, ),annotations=arrow_list)

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: python pandas dataframe annotations plotly


    【解决方案1】:

    好的。所以我想我知道这里出了什么问题。这是一个愚蠢的错误。我的箭头字典的“x”值错误。

    目前是:

    arrow=dict(x=df['Headline'].values[counter]....
    

    但应该是:

    arrow=dict(x=df['date'].values[counter]....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-24
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      相关资源
      最近更新 更多