我在 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()
- 每当您指定
row
或col
参数时,内部方法都会有效地返回一个空列表。之后,代码变得更具挑战性。这似乎是一个错误 - 作为解决方法,您可以使用带有
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)
关于python - 在 Python 中,如何使用 'update_annotations' 更新 plotly 数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71716047/