Plotly - 在创建轨迹后更新子图标题

12

我有一个由子图组成的Plotly图表 -

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 或类似的方式来实现吗?


也许一个更好的结构可以是 https://plotly.com/python/figure-factories/。 - giammi56
似乎还存在一个结构性问题:https://github.com/plotly/plotly.py/issues/2483#issuecomment-630889399 - giammi56
4个回答

8
当使用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()

enter image description here


1
您可以按如下方式遍历x轴。这将在每个子图上设置x轴标题:
for i in range(3):
    fig['layout'][f'xaxis{i+1}'].update(title=f'Title {i+1}')

关于设置相关问题,如何在每个轴上设置showgridPlotly set showgrid = False for ALL subplots


0
在make_subplot期间,指定任何标题,只要不是空字符串即可。这将负责计算注释的正确x和y坐标,这样您就不必像@jayveesea的回答中那样自己解决了。
以后只需在适当时更改标题文本即可。
子图的标题实际上是注释"text"。以防您没有看到标题一词。 :-)
import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = make_subplots(rows=3, cols=1, subplot_titles=[" ", " ", " "])

fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=1, col=1)
fig.layout.annotations[0].update(text="My Title 1")

fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=2, col=1)
fig.layout.annotations[1].update(text="My Title 2")

fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=3, col=1)      
fig.layout.annotations[2].update(text="My Title 3")

fig.show()

Example with several subplots


-1

试试这个,

fig.update_layout(margin=dict(l=20, r=20, t=20, b=20), paper_bgcolor="LightSteelBlue", xaxis_title='X Label Name', yaxis_title="Y Label Name")

2
谢谢,我想要更新每个子图的标题,而不是轴标题。 - Tom Ron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接