Black Lives Matter. Please consider donating to Black Girls Code today.

Setting titles for subplots and adding annotations

Hi guys,

I am trying to set titles to subplots and adding annotations to the first subplot - using plotly 4.0.

fig = make_subplots(
rows=3, cols=1,
shared_xaxes=True,
shared_yaxes=False,
vertical_spacing=0.02,
subplot_titles=(“bla”,
“bla bla”)

works fine for adding the titles, but as soon as I add annotations with

annotations=[
dict(
x=10,
y=150,
xref=“x”,
yref=“y”,
text='some text,
showarrow=True,
ax=20,
ay=-30
),
dict(
x=10,
y=150,
xref=“x”,
yref=“y”,
text='some text,
showarrow=True,
ax=20,
ay=-30
) ]
fig.layout.annotations=annotations

the titles disappear and the annotations appear.

My Workaround is extending the annotations with my subplot titles

annotations.extend([
dict(
showarrow=False,
xref=“paper”,
yref=“paper”,
x= 0.5,
y= 1.01,
text= ‘subplot title 1’
),
dict(
showarrow=False,
xref=“paper”,
yref=“paper”,
x= 0.5,
y= 0.93,
text= ‘subplot title 2’
)]
)

But it feels very awkward and I am sure there is another way to set the position than guessing it via the ‘paper’ reference, but I just don’t know how.
Does anyone know how to solve this problem with the subplot_titles and annotations?

Cheers
Nils

Hey @nilsfl,

Sorry I don’t have much time to be too detailed in my answer but I was searching through posts and thought I could chime in with some insight

The reason, that the subplot titles disappear when you define the annotation is that you are overriding the already existing annotations created by the make_subplots method, which is where the subplot titles are stored

Seems like you already figured that out with your .extend approach

The better way of adding subplot axis titles is to use the update_xaxes method attached to subplots, and update the title_text attribute