我在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
参数,内部方法都会有效地返回一个空列表。在那之后,代码变得更具挑战性。这似乎是一个错误 - 作为解决方案,您可以将
update_annotations()
与selector
参数一起使用。在下面的代码中演示
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)