首页 > 解决方案 > Plotly - 在跟踪 createtd 后更新子图标题

问题描述

我有一个由子图组成的情节 -

fig = make_subplots(
        rows=3, cols=1)

fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=1, col=1)
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=2, col=1)
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=3, col=1)

我要为每个子图添加一个标题,但只有在创建了图形并添加了跟踪之后。即不是当我创建图形时 -

fig = make_subplots(
            rows=3, cols=1, subplot_titles=['a', 'b', 'c']

我可以通过fig.update_layout或类似的方式来做吗?

标签: pythonplotly

解决方案


使用时make_subplots,它会创建(正确放置)注释。因此,这可以大部分使用注释方法进行复制。一般来说,对于第一个:

fig.add_annotation(xref="x domain",yref="y domain",x=0.5, y=1.2, showarrow=False,
                   text="a", row=1, col=1)

缺点是您可能需要根据自己xy条件/口味进行调整。

完整示例,使用粗体文本:

import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = make_subplots(rows=3, cols=1)
    
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=1, col=1)
fig.add_annotation(xref="x domain",yref="y domain",x=0.5, y=1.2, showarrow=False,
                   text="<b>Hey</b>", row=1, col=1)

fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=2, col=1)
fig.add_annotation(xref="x domain",yref="y domain",x=0.5, y=1.2, showarrow=False,
                   text="<b>Bee</b>", row=2, col=1)

fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=3, col=1)
fig.add_annotation(xref="x domain",yref="y domain",x=0.5, y=1.2, showarrow=False,
                   text="<b>See</b>", row=3, col=1)

fig.show()

在此处输入图像描述


推荐阅读