✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🧬 Learn how to build RNA-Seq data apps with Python & Dash. Register for the May 20 Webinar!

Can I add figures to a subplot?

I’ve written a few functions that create various figures (they return a go.Figure() instance). I want to be able to compose these in various ways into subplots so I won’t know ahead of time what the row and column of each figure should be. I was hoping to do something like:

fig = make_subplots(rows=2, cols=1)
f1 = create_return_figure(data)
f2 = create_volatility_figure(data)
fig.add_trace(f1, 1, 1)
fig.add_trace(f2, 2, 1)

But that doesn’t work since you can’t add a figure to a figure. I’m probably just misunderstanding this but I haven’t found an example that does what I’m trying to do.

Unfortunately there’s no way today of composing multiple figures into one, and there’s not really a general-purpose recipe for doing this either. You basically have to start from a make_subplots call and add your traces to the appropriate subplots rather than create multiple independent figures and try to combine them.

Thanks. Ultimately, I wanted this in HTML so subplots weren’t strictly necessary. Based on an SO post I’ve solved it a different way that’s suitable for my needs:

def save_figures_to_html(figures, html_template, filename):
    import plotly.offline as pyo

    include_js = "cdn"
    fightml = []
    for fig in figures:
        fightml.append(pyo.plot(fig, include_plotlyjs=include_js, output_type='div'))
        include_js = False

    with open(filename, 'w') as f:
        f.write(html_template.format(*fightml))

I can then manage the row/column layout in the HTML template.

html_template = """
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
</head>
<body>
<div class="container">
  <div class="row">
    <div class="col">{}</div>
    <div class="col">{}</div>
  </div>
  <div class="row">
    <div class="col">{}</div>
    <div class="col">{}</div>
  </div>
  <div class="row">
    <div class="col">{}</div>
    <div class="col">{}</div>
  </div>
  <div class="row">
    <div class="col">{}</div>
    <div class="col">{}</div>
  </div>
  <div class="row">
    <div class="col">{}</div>
  </div>
</div>
</body>
</html>
"""

save_figures_to_html([f1, f2, f3, f4, f5, f6, f7, f8, f9], html_template, 'report.html')