Add subplot title in low-level API

I am trying to add a different title to each subplot. These are not made with make_subplots(), but instead using the low-level API documented here: so I cannot add the subplot titles in the argument subplot_titles. Is there a way to add subplot titles in the low-level API?

trace1 = go.Scatter(
    x=[1, 2, 3],
    y=[4, 5, 6]
)
trace2 = go.Scatter(
    x=[20, 30, 40],
    y=[50, 60, 70],
    xaxis="x2",
    yaxis="y2"
)
data = [trace1, trace2]
layout = go.Layout(
    xaxis=dict(
        domain=[0, 0.7]
    ),
    xaxis2=dict(
        domain=[0.8, 1]
    ),
    yaxis2=dict(
        anchor="x2"
    )
)
fig = go.Figure(data=data, layout=layout)
fig.show()

Hi @franjuanele,

Yes, there is a way to create subplot title without make_subplot().

Subplot titles that made by make_subplots() is actually a text annotations.
So,you can create one by using text annotations.

To make centered subplot title you must set x,y position and x,y anchor manually.

If I update your code, it will be like code below.

from plotly import graph_objects as go

trace1 = go.Scatter(
    x=[1, 2, 3],
    y=[4, 5, 6],
)
trace2 = go.Scatter(
    x=[20, 30, 40],
    y=[50, 60, 70],
    xaxis="x2",
    yaxis="y2",
)
data = [trace1, trace2]
layout = go.Layout(
    xaxis=dict(
        domain=[0, 0.7]
    ),
    xaxis2=dict(
        domain=[0.8, 1]
    ),
    yaxis2=dict(
        anchor="x2"
    )

) 

fig = go.Figure(data=data, layout=layout)

# create subplot title using text annotations
# set position of titles on each subplots
x_pos1 = sum(layout["xaxis"]["domain"])/2 # get center x pos value from domain
x_pos2 = sum(layout["xaxis2"]["domain"])/2 # get center x pos value from domain
y_pos1 = y_pos2 = 1
subplot_titles = [(x_pos1,y_pos1,"Subplot 1"),(x_pos2,y_pos2,"Subplot 2")]

# create annotations
annotations = [{
                "y": y_pos,
                "xref": "paper",
                "x": x_pos,
                "yref": "paper",
                "text": title,
                "showarrow": False,
                "font": dict(size=16),
                "xanchor": "center",
                "yanchor": "bottom",
            } for x_pos,y_pos,title in subplot_titles]

# update annotations on layout
fig.update_layout(annotations=annotations)

fig.show()

Hope this help.

2 Likes