Plotly - update subplot titles after traces where createtd

Viewed 1694

I have a plotly plot composed of 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_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)

I was to add a title for every the subplots but only after the figure is created and the traces are added. I.e not when I create the figure -

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

Can I do it via fig.update_layout or something similar?

3 Answers

When make_subplots is used it's creating (correctly placed) annotations. So this can be mostly duplicated using annotation methods. In general, for the first:

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

The downside is you may need to adjust x and y to your conditions/tastes.

Full example, using bold text:

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

You can iterate through the xaxes as follows. This sets the x axis title on each subgraph:

for i in range(3):
    fig['layout'][f'xaxis{i+1}'].update(title=f'Title {i+1}')

Related question setting showgrid on each axis: Plotly set showgrid = False for ALL subplots

Try this,

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")
Related