简体   繁体   中英

Plotly - update subplot titles after traces where createtd

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. Ie 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?

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()

在此处输入图片说明

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

尝试这个,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM