在 Python 中,如何使用 'update_annotations' 更新 plotly 数字?

In Python, how can I update plotly figures using 'update_annotations'?

我在 python 中使用 Plotly 来生成数字。如标题所示,我无法使用 update_annotations 函数更新图形注释。

下面是多图的例子。

data = pd.DataFrame(np.random.rand(10,3), columns=['A', 'B', 'C'], index=pd.date_range(start='2001-01-01', periods=10))

fig = make_subplots(rows=3, cols=1, subplot_titles=['Top','Middle', 'Bottom'])

fig.add_trace(go.Scatter(x=data.index, y=data['A'], mode='lines'), row=1, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data['B'], mode='lines'), row=2, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data['C'], mode='lines'), row=3, col=1)

我可以使用以下代码将顶部图形的名称从 'TOP' 更改为 'TOP_TEST' 及其位置。

fig['layout']['annotations'][0]['text'] = 'TOP_TEST'
fig['layout']['annotations'][0]['x'] = 0.02

但是,我不明白为什么我不能对函数update_annotations做同样的事情。如果可行,一次更改多个参数似乎更容易。

fig.update_annotations(row=1, col=1, text='TOP_TEST', x=0.02)

感谢您提前发表评论。

  • 已查看 plotly 代码。 update_annotations() 使用 _select_annotations_like()
  • 每当您指定 rowcol 参数时,内部方法 returns 实际上是一个空列表。之后,代码变得更具挑战性。这似乎是一个错误
  • 作为解决方法,您可以使用带有 selector 参数的 update_annotations()。在下面的代码中演示
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.express as px


data = pd.DataFrame(np.random.rand(10,3), columns=['A', 'B', 'C'], index=pd.date_range(start='2001-01-01', periods=10))

fig = make_subplots(rows=3, cols=1, subplot_titles=['Top','Middle', 'Bottom'])

fig.add_trace(go.Scatter(x=data.index, y=data['A'], mode='lines'), row=1, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data['B'], mode='lines'), row=2, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data['C'], mode='lines'), row=3, col=1)

# empty so nothing to update...
list(fig._select_annotations_like(prop="annotations", row=1, col=1))

# select based on text on we're ok
fig.update_annotations(selector={"text":"Top"}, text="TOP_TEST", x=.02)