ZetCode

Python Panel

last modified November 30, 2026 Python 3.15

In this article we show how to build interactive web applications with the Panel library.

Panel is an open-source library from the HoloViz project. It creates web apps and dashboards entirely in Python: we combine text, tables, plots, and widgets into layouts, and Panel renders them in the browser. When a user changes a widget, the browser sends the new value to the Python process, which runs our code and sends back the updated content. Panel is built on the Bokeh library, which provides the server and the browser components.

A Panel app consists of three kinds of objects. Panes display content such as Markdown, HTML, DataFrames, or plots; widgets such as sliders and buttons take input; and layouts such as Row, Column, and Tabs arrange the other objects.

The examples were tested with Panel 1.11.1, Bokeh 3.10.2, pandas 3.1, and Matplotlib 3.11. The screenshots were taken in Chromium.

$ pip install panel pandas matplotlib

The first app

The smallest Panel app shows one pane. We mark the object that forms the page with the servable method.

first_app.py
import panel as pn

pn.extension()

pn.pane.Markdown('''
# Falcons

Falcons are birds of prey. The **peregrine falcon** is the
fastest animal on Earth.
''').servable()

The pn.extension call loads the JavaScript and CSS that Panel needs in the browser; every app calls it once, near the top. The pn.pane.Markdown pane renders Markdown text as HTML.

The servable method marks the pane as the content of the page when the script runs on the Panel server. Running the script with plain python does nothing visible. Instead, we start the server with the panel serve command, which runs the script for each browser session. The app is then available at http://localhost:5006/first_app; the server runs until we stop it with Ctrl+C. With the --dev option, the server reloads the app whenever the file changes, which is handy during development.

For quick experiments, objects also have a show method, which starts a server from a running Python program and opens the page in a browser. In Jupyter notebooks, Panel objects are displayed directly in the notebook.

$ panel serve first_app.py
2026-11-30 19:53:45,193 Starting Bokeh server version 3.10.2 (running on Tornado 6.6.1)
2026-11-30 19:53:45,196 Bokeh app running at: http://localhost:5006/first_app
2026-11-30 19:53:45,196 Starting Bokeh server with process id: 33891

Interrupted, shutting down

The first app in the browser

The page shows the rendered Markdown: a heading and a paragraph with bold text.

Markdown pane in Panel
Figure: Markdown pane in Panel

Layouts and widgets

Layouts hold other Panel objects, and widgets keep their current state in the value parameter. Both are ordinary Python objects, so we can build and inspect them without a browser.

layout_tree.py
import panel as pn

title = pn.pane.Markdown('# Weather')
city = pn.widgets.TextInput(label='City', value='Bratislava')
days = pn.widgets.IntSlider(label='Days', start=1, end=14, value=7)

layout = pn.Column(title, pn.Row(city, days))

print(layout)
print(city.value, days.value)

days.value = 10
print(days.value)

We create a Markdown pane, a text input, and an integer slider, and put them into a Column with a nested Row. Printing a layout shows its tree of objects. The value parameter of a widget is read and set like an attribute; in an app, setting it from Python also moves the widget in the browser.

The label parameter sets the text shown above a widget. Older code uses the name parameter for this; in Panel 1.11 it is deprecated and Panel issues a warning when it is used.

$ python layout_tree.py
Column
    [0] Markdown(str)
    [1] Row
        [0] TextInput(label='City', name='City', value='Bratislava', value_input='Bratislava')
        [1] IntSlider(end=14, label='Days', name='Days', start=1, value=7)
Bratislava 7
10

Binding widgets to a function

The pn.bind function connects widgets to an ordinary function. Panel calls the function with the current widget values and calls it again whenever one of them changes.

greeting.py
import panel as pn

pn.extension()

name = pn.widgets.TextInput(label='Name', value='Peter')
times = pn.widgets.IntSlider(label='Times', start=1, end=5, value=2)

def greet(name, times):
    lines = [f'Hello there, **{name}**!'] * times
    return '\n\n'.join(lines)

message = pn.pane.Markdown(pn.bind(greet, name, times))

pn.Column(name, times, message).servable()

The greet function knows nothing about Panel; it receives a name and a number and returns a Markdown string. The pn.bind(greet, name, times) call returns a bound function, and the Markdown pane displays its result. When we type a new name and press Enter, or move the slider, Panel calls greet again and the pane updates.

In the screenshot, we have changed the name to Lucia and moved the slider to 3.

Widgets bound to a function
Figure: Widgets bound to a function

Button callbacks

A button has no value to bind to. Instead, we register a callback with the on_click method, which Panel calls on every click.

counter.py
import panel as pn

pn.extension()

clicks = 0
button = pn.widgets.Button(label='Add', button_type='primary')
reset = pn.widgets.Button(label='Reset')
status = pn.pane.Markdown('Clicked 0 times')

def add(event):
    global clicks
    clicks += 1
    status.object = f'Clicked {clicks} times'

def clear(event):
    global clicks
    clicks = 0
    status.object = 'Clicked 0 times'

button.on_click(add)
reset.on_click(clear)

pn.Column(pn.Row(button, reset), status).servable()

The callbacks receive an event object, which we do not need here. They change the module-level clicks counter and update the Markdown pane by setting its object parameter, which holds the displayed content. The button_type parameter gives the Add button its colour.

The panel serve command runs the script separately for each browser session, so every visitor gets their own widgets and their own counter. The screenshot shows the app after three clicks on the Add button.

Button callbacks
Figure: Button callbacks

Tabs

The Tabs layout shows one of several objects at a time. It takes pairs of a tab title and its content.

tabs_layout.py
import panel as pn

pn.extension()

about = pn.pane.Markdown('''
### Wind turbines

A wind turbine converts the kinetic energy of wind into
electrical energy.
''')

parts = pn.pane.Markdown('''
| Part | Purpose |
| --- | --- |
| Rotor | catches the wind |
| Gearbox | raises the speed |
| Generator | produces electricity |
''')

speed = pn.widgets.FloatSlider(label='Wind speed (m/s)', start=0, end=25,
                               step=0.5, value=8)

def estimate(speed):
    return f'Estimated power: **{0.3 * speed ** 3:.0f} kW**'

calculator = pn.Column(speed, pn.pane.Markdown(pn.bind(estimate, speed)))

tabs = pn.Tabs(('About', about), ('Parts', parts), ('Calculator', calculator))

pn.Column('## Wind energy', tabs, width=420).servable()

The first two tabs hold Markdown panes; the second one contains a Markdown table. The third tab holds a small calculator: a float slider bound to the estimate function, which computes the power of a turbine from the wind speed. A plain string in a layout, such as '## Wind energy', is turned into a Markdown pane automatically. The width parameter fixes the width of the column in pixels.

Tabs layout
Figure: Tabs layout

Filtering a DataFrame

The Tabulator widget displays a pandas DataFrame as an interactive table, which can be sorted by clicking a column header. We filter its rows with a select box.

cities_table.py
import pandas as pd
import panel as pn

pn.extension('tabulator')

df = pd.DataFrame({
    'city': ['Bratislava', 'Kosice', 'Budapest', 'Debrecen', 'Prague',
             'Brno', 'Vienna', 'Graz'],
    'country': ['Slovakia', 'Slovakia', 'Hungary', 'Hungary', 'Czechia',
                'Czechia', 'Austria', 'Austria'],
    'population': [475503, 228249, 1686222, 199520, 1384732, 402739,
                   2028399, 305314],
})

country = pn.widgets.Select(label='Country',
                            options=['All'] + sorted(df['country'].unique()))

def select_rows(country):
    if country == 'All':
        return df
    return df[df['country'] == country]

def total(country):
    return f'Total population: {select_rows(country)["population"].sum():,}'

table = pn.widgets.Tabulator(pn.bind(select_rows, country),
                             show_index=False, width=380)

pn.Column(country, table, pn.pane.Markdown(pn.bind(total, country))).servable()

The Tabulator widget needs an extra JavaScript library, so we name it in the pn.extension('tabulator') call. The Select widget offers All and the sorted list of countries.

The select_rows function returns the DataFrame or a part of it, and we pass the bound function directly to the table: widgets, like panes, accept bound functions in place of their values. The second bound function computes the total population of the shown cities. The screenshot shows the app after selecting Hungary.

Filtered Tabulator table
Figure: Filtered Tabulator table

Interactive plot

The Matplotlib pane displays a Matplotlib figure. When the figure comes from a bound function, the plot is redrawn every time a widget changes.

sine_plot.py
import numpy as np
import panel as pn
from matplotlib.figure import Figure

pn.extension()

frequency = pn.widgets.FloatSlider(label='Frequency', start=0.5, end=5,
                                   step=0.5, value=1)
amplitude = pn.widgets.FloatSlider(label='Amplitude', start=0.5, end=2,
                                   step=0.25, value=1)

def plot_wave(frequency, amplitude):
    x = np.linspace(0, 2 * np.pi, 400)
    fig = Figure(figsize=(6, 3))
    ax = fig.subplots()
    ax.plot(x, amplitude * np.sin(frequency * x))
    ax.set_ylim(-2.2, 2.2)
    ax.set_title(f'{amplitude} * sin({frequency} * x)')
    ax.grid(True)
    return fig

plot = pn.pane.Matplotlib(pn.bind(plot_wave, frequency, amplitude),
                          dpi=96, tight=True)

pn.Row(pn.Column(frequency, amplitude, width=250), plot).servable()

The plot_wave function draws a sine wave with the given frequency and amplitude. We create the figure with the Figure class instead of pyplot; figures made by pyplot are kept in a global list until they are closed, which in a server process that redraws the plot often would leak memory. A fixed y range makes the changes of amplitude visible.

The dpi parameter of the pane sets the resolution of the image, and tight=True removes the empty space around the plot. The screenshot shows the frequency raised to 2.5.

Matplotlib plot bound to sliders
Figure: Matplotlib plot bound to sliders

Saving to a static HTML file

A Panel layout can be saved to an HTML file that works without a Python server. With embed=True, Panel computes the output for each widget value in advance and stores the results in the file.

save_report.py
import panel as pn

pn.extension()

level = pn.widgets.IntSlider(label='Level', start=1, end=3, value=1)

def describe(level):
    names = {1: 'beginner', 2: 'intermediate', 3: 'expert'}
    return f'Selected level: **{names[level]}**'

report = pn.Column(
    '# Course levels',
    'Move the slider to see the name of each level.',
    level,
    pn.pane.Markdown(pn.bind(describe, level)),
)

report.save('levels.html', embed=True, title='Course levels', progress=False)

with open('levels.html', encoding='utf-8') as f:
    page = f.read()

print(f'{len(page):,} characters')
for name in ('beginner', 'intermediate', 'expert'):
    print(name, name in page)

The slider has three values, so Panel calls describe three times while saving and embeds all three results in the page; the browser then switches between them without Python. The progress=False option turns off the progress bar printed during this step. The page loads the Panel and Bokeh JavaScript files from a CDN, which keeps it small. With resources='inline', they are included in the file, which then works offline.

Embedding works only for widgets with a small number of values, because every combination of values must be computed in advance. Apps that compute their output from free text input or large ranges need the Panel server.

$ python save_report.py
17,346 characters
beginner True
intermediate True
expert True

A dashboard with a template

Templates give an app a complete page layout with a header, a sidebar, and a main area. We use the FastListTemplate to build a small dashboard of monthly temperatures.

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

pn.extension('tabulator')

MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

df = pd.DataFrame({
    'month': MONTHS,
    'Bratislava': [0, 2, 6, 12, 16, 20, 22, 22, 17, 11, 5, 1],
    'Oslo': [-4, -4, 0, 5, 11, 15, 17, 16, 11, 6, 1, -3],
    'Lisbon': [12, 13, 15, 16, 18, 21, 23, 23, 22, 19, 15, 13],
})

cities = pn.widgets.MultiChoice(label='Cities', options=list(df.columns[1:]),
                                value=['Bratislava', 'Oslo'])
months = pn.widgets.IntRangeSlider(label='Months', start=1, end=12,
                                   value=(1, 12))

def select(cities, months):
    first, last = months
    return df.iloc[first - 1:last][['month'] + cities]

def plot(cities, months):
    data = select(cities, months)
    fig = Figure(figsize=(7, 3.5))
    ax = fig.subplots()
    for city in cities:
        ax.plot(data['month'], data[city], marker='o', label=city)
    ax.set_ylabel('Average temperature (°C)')
    ax.grid(True)
    if cities:
        ax.legend()
    return fig

def summary(cities, months):
    data = select(cities, months)
    lines = [f'- **{city}**: {data[city].mean():.1f} °C' for city in cities]
    return '### Mean temperature\n\n' + '\n'.join(lines)

template = pn.template.FastListTemplate(
    title='Monthly temperatures',
    sidebar=[cities, months, pn.pane.Markdown(pn.bind(summary, cities, months))],
    main=[
        pn.pane.Matplotlib(pn.bind(plot, cities, months), dpi=96, tight=True),
        pn.widgets.Tabulator(pn.bind(select, cities, months),
                             show_index=False, height=250),
    ],
)

template.servable()

The sidebar holds a MultiChoice widget for selecting cities, an IntRangeSlider for the range of months, and a summary of the mean temperatures. The main area shows a line plot and a table. All three outputs are bound to the same two widgets and are computed from the select function, which returns the chosen rows and columns of the DataFrame.

The template adds a header with the title, a button that hides the sidebar, and a switch between the light and the dark theme. The screenshot shows the months limited to January to August.

Dashboard with FastListTemplate
Figure: Dashboard with FastListTemplate

Source

Panel documentation, Panel component gallery

In this article we have built web apps with Panel. We have displayed Markdown, arranged objects in rows, columns, and tabs, bound widgets to functions with pn.bind, handled button clicks, filtered a DataFrame in a Tabulator table, redrawn a Matplotlib plot, saved an app to a static HTML file, and created a dashboard with a template. For the data and plotting side, see the Pandas tutorial, Python DataFrame, and the Matplotlib tutorial.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.