Skip to content

Instantly share code, notes, and snippets.

@MBulli
Last active December 13, 2022 09:18
Show Gist options
  • Save MBulli/10c2341460bb1cdd23f75d21cc486ab2 to your computer and use it in GitHub Desktop.
Save MBulli/10c2341460bb1cdd23f75d21cc486ab2 to your computer and use it in GitHub Desktop.
Plotly Python: Arrange subplots in a grid layout
def grid_layout_subplots(traces: typing.List[go.Trace], titles: typing.List[str] = None, ncolumns: int = 1, fig: go.Figure = None) -> go.Figure:
if fig is None:
fig = go.Figure()
ncolumns = int(min(ncolumns, len(traces)))
if ncolumns == 0:
return fig
nrows = int(math.ceil(len(traces) / ncolumns))
fig.set_subplots(nrows, ncolumns, subplot_titles=titles)
for idx, t in enumerate(traces):
col = int((idx % ncolumns))+1
row = int(idx / ncolumns)+1
# if nested list: plot them in a shared axis
if type(t) is list:
for t_ in t:
fig.add_trace(t_, row=row, col=col)
else:
fig.add_trace(t, row=row, col=col)
return fig
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment