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

标签 python plotly

我在 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 参数时,内部方法都会有效地返回一个空列表。之后,代码变得更具挑战性。这似乎是一个错误
  • 作为解决方法,您可以使用带有 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/

相关文章:

python - 在 Flask 应用程序中绘图以测量实时数据

javascript - 时间模式下的 Plot.ly : fixed grid size

python - 如何巧妙地不忽略我的轴设置?

python - 如果 __name__ == "__main__":,则托管在 Apache 上的 web.py 不会在旁边运行代码

python - 从 pandas df 更新数据库中的现有行

python - 如何以绘图方式格式化数字并避免转换为百万

python - 如何使用 Plotly (Python) 中的 Candlestick 制作动画

python - 如何使用不同的数据集进行 GridSearchCV 训练和测试?

Python Twisted - 如何通过已连接的套接字连接发送数据?

python - Tensorflow 梯度 : without automatic implicit sum