Search code examples
pythonplotlysubplot

python plotly - arranging odd number of subplots


Toy example:

import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = make_subplots(rows=2, cols=3,
                    shared_yaxes=True,
                   horizontal_spacing=0.02)

fig.add_scatter(x=[1,2,3],y=[1,2,3], row=1, col=1)
fig.add_scatter(x=[1,2,3],y=[1,2,3], row=1, col=2)
fig.add_scatter(x=[1,2,3],y=[1,2,3], row=1, col=3)
fig.add_scatter(x=[1,2,3],y=[1,2,3], row=2, col=1)
fig.add_scatter(x=[1,2,3],y=[1,2,3], row=2, col=2)

fig.update_layout(showlegend=False)
fig.show()

enter image description here

I would like to push the two subplots in the bottom row to the right, so they are placed in the middle. Something like this: enter image description here

Is there a way to do it programatically? I've tried playing with the specs option of make_subplots, but without success.


Solution

  • I have set up your subplot based on the examples in the reference. To center the graph of the second row in this case, use two columns, each with five rows in the first row. The second row uses two columns for the second and third rows. None, which is not in the graph, must be included in the number of columns.

    from plotly.subplots import make_subplots
    import plotly.graph_objects as go
    
    fig = make_subplots(
        rows=2, cols=6,
        specs=[
            [{'colspan': 2}, None, {'colspan': 2}, None, {'colspan': 2},None],
            [None, {'colspan': 2}, None, {'colspan': 2}, None, None]
              ],
        shared_yaxes=True,
        horizontal_spacing=0.02,
        print_grid=True)
    
    fig.add_scatter(x=[1,2,3],y=[1,2,3], row=1, col=1)
    fig.add_scatter(x=[1,2,3],y=[1,2,3], row=1, col=3)
    fig.add_scatter(x=[1,2,3],y=[1,2,3], row=1, col=5)
    fig.add_scatter(x=[1,2,3],y=[1,2,3], row=2, col=2)
    fig.add_scatter(x=[1,2,3],y=[1,2,3], row=2, col=4)
    
    fig.update_layout(showlegend=False)
    fig.show()
    
    This is the format of your plot grid:
    [ (1,1) x,y             -      ]  [ (1,3) x2,y2           -      ]  [ (1,5) x3,y3           -      ]
        (empty)      [ (2,2) x4,y4           -      ]  [ (2,4) x5,y5           -      ]      (empty)    
    

    enter image description here