Tight layout of matplotlib figures in pn.Row

Started writing this and solved it. Sharing for others.

import matplotlib.pyplot as plt
import pandas as pd
import panel as pn

pn.extension(sizing_mode="scale_width")

pn.panel("# Title").servable()

df = pd.DataFrame({"a": [0, 1]})

fig0, ax0 = plt.subplots()
df["a"].plot(ax=ax0)
fig1, ax1 = plt.subplots()
df["a"].plot(ax=ax1)
fig2, ax2 = plt.subplots()
df["a"].plot(ax=ax2)

pn.panel(pn.Row(fig0, fig1, fig2)).servable()

Thanks for sharing @raybellwaves

You can simplify by replacing pn.panel(pn.Row(fig0, fig1, fig2)).servable() by pn.Row(fig0, fig1, fig2).servable(). pn.panel wraps your non-Panel Python object into the relevant pane for rendering. Its similar to st.write that determines which st.XYZ command to use.

(both versions looks like below)

1 Like

Another small thing is that it is better to use from matplotlib.figure import Figure, especially when you are in a notebook. See here.

1 Like

Thanks. Any idea how to use it with the pandas plot examples above?

Is this what you are looking for @raybellwaves ?

import pandas as pd
import panel as pn
from matplotlib.figure import Figure

pn.extension(sizing_mode="scale_width", template="fast")

pn.panel("# Title").servable()

df = pd.DataFrame({"a": [0, 1]})

fig0 = Figure()
ax0=fig0.subplots()
df["a"].plot(ax=ax0)
fig1 = Figure()
ax1=fig1.subplots()
df["a"].plot(ax=ax1)
fig2 = Figure()
ax2=fig2.subplots()
df["a"].plot(ax=ax2)

pn.panel(pn.Row(fig0, fig1, fig2)).servable()
2 Likes

You can also change the last line to pn.Row(fig0, fig1, fig2).serveable (thanks to you!)

2 Likes