In python Panel, how to show a matplotlib plot in a panel.Tabs view?

426 views Asked by At

The Python Panel library recommends using Bokeh for plotting, but some statistical figures are lacking from the Bokeh package. I want to use matplotlib (or maybe seaborn) to create figures that I can place in panel.Tabs.

For example, the following code works but uses Bokeh instead of matplotlib:

import panel as pn
from bokeh.plotting import figure

p1 = figure(width=400, height=400, name="Line 1")
p1.line([1, 2, 3], [1, 2, 3])

p2 = figure(width=400, height=400, name='Line 2')
p2.line([0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 2, 1, 0])

pn.Tabs(p1, p2)

This (correctly) shows:

enter image description here

However, every attempt I made to show an image from matplotlib failed. Something like p1 = plt.plot(df['wage']) simply does not work.

1

There are 1 answers

0
Davide_sd On

Holoviz Panel uses the concept of panes to render figures (plotly figures, bokeh figures, matplotlib figures)... For example, to render a matplotlib figure you have to use pn.pane.Matplotlib (here is its documentation).

Note that it requires the figure to be created with matplotlib.figure.Figure instead of the more traditional plt.figure.

import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import panel as pn
pn.extension()

fig1 = Figure()
ax1 = fig1.subplots()
ax1.plot([1, 2, 3], [1, 2, 3])

fig2 = Figure()
ax2 = fig2.subplots()
ax2.plot([0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 2, 1, 0])

pane1 = pn.pane.Matplotlib(fig1, dpi=96)
pane2 = pn.pane.Matplotlib(fig2, dpi=96)
pn.Tabs(("title 1", pane1), ("title 2", pane2))