如何在堆积面积图中添加最后一个值的注释?

how to add annotation of last value in stacked area chart?

我使用 stackgroup= 创建了堆积面积图,现在我想为最后一个值添加注释。

我正在从这里复制代码并进行一些修改。

这是堆叠面积图的原始图

for ipad,pad in enumerate(pad_list):
    for iwell,well in enumerate(cols_thispad):
        fig.add_scatter(
            x=df.index,
            y=df[well].values, 
            mode='lines',
            line={"color": colors_discrete[iwell]},  #"color": "#035593"
            stackgroup=str(ipad+1), # define stack group
            name=well,
            row=ipad+1,
            col=1,
            legendgroup = str(ipad+1),
            meta=well,
            text=[key.title()+unit_thiskey]*len(df.index),
            hovertemplate='%{meta}<br>Datetime: %{x}<br>%{text}:%{y}<extra></extra>',  
            )

绘图后,我想为每个堆叠区域聊天的最后一个值添加注释,这是我所做的,如果我使用 stackgroup=,则绘图是完全错误的。如果我在下面的聊天中删除 stackgroup=,则可以在右图中显示最后的值。但是,它没有堆叠。那么如何在堆栈模式下显示最后一个值标记呢?谢谢

    for i, d in enumerate(fig.data):

        padname=d.name.split('A')[1][:2]
        padname_ix=pad_list.index(padname)
        legendgroup=str(padname_ix+1)
        row=padname_ix+1
        stackgroup=str(padname_ix+1)
             
        fig.add_scatter(x=[d.x[-1]], y = [d.y[-1]],
                        mode = 'markers+text',
                        text = f'{d.y[-1]:.2f}',
                        textfont = dict(color=d.line.color),
                        textposition='middle right',
                        marker = dict(color = d.line.color, size = 12),
                        legendgroup = legendgroup, #d.name,\
                        stackgroup=stackgroup,
                        row=row,col=1,
                        showlegend=False) 

这是在第二个代码中没有使用堆栈组的情节。它有效但不正确。

由于此函数对堆叠图进行分组,因此可以通过为每个组单元指定一个唯一名称来解决该问题。在示例答案中,面积图被命名为 'one' 并且散点图的文本注释被命名为 'two'.

import yfinance as yf
ticker = ['AAPL','GOOGL','TSLA','MSFT']
data = yf.download(ticker, start="2021-01-01", end="2021-03-01")['Close']

import plotly.graph_objects as go

fig = go.Figure()
for t in data.columns:
    fig.add_trace(go.Scatter(x=data.index,
                             y=data[t],
                             hoverinfo='x+y',
                             mode='lines',
                             stackgroup='one',
                             name=t
                            )
                 )
    
    fig.add_trace(go.Scatter(x=[data.index[-1]],
                             y=[data[t][-1]],
                             mode='markers+text',
                             text=round(data[t][-1],2),
                             textposition='middle left',
                             stackgroup='two',
                             name=t,
                             showlegend=False
                            )
                 )
fig.update_layout(height=600
                 )
fig.show()