Panel lets you add interactive controls for just about anything you can display in Python. Panel can help you build simple interactive apps, complex multi-page dashboards, or anything in between. As a simple example, let's say we have loaded the UCI ML dataset measuring the environment in a meeting room:
import pandas as pd; import numpy as np; import matplotlib.pyplot as plt
data = pd.read_csv('../assets/occupancy.csv')
data['date'] = data.date.astype('datetime64[ns]')
data = data.set_index('date')
data.tail()
And we've written some code that smooths a time series and plots it using Matplotlib with outliers highlighted:
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvas
%matplotlib inline
def mpl_plot(avg, highlight):
fig = Figure()
FigureCanvas(fig) # not needed in mpl >= 3.1
ax = fig.add_subplot()
avg.plot(ax=ax)
if len(highlight): highlight.plot(style='o', ax=ax)
return fig
def find_outliers(variable='Temperature', window=30, sigma=10, view_fn=mpl_plot):
avg = data[variable].rolling(window=window).mean()
residual = data[variable] - avg
std = residual.rolling(window=window).std()
outliers = (np.abs(residual) > std * sigma)
return view_fn(avg, avg[outliers])
We can call the function with parameters and get a plot:
find_outliers(variable='Temperature', window=20, sigma=10)
It works! But exploring all these parameters by typing Python is slow and tedious. Plus we want our boss, or the boss's boss, to be able to try it out.
If we wanted to try out lots of combinations of these values to understand how the window and sigma affect the plot, we could reevaluate the above cell lots of times, but that would be a slow and painful process, and is only really appropriate for users who are comfortable with editing Python code. In the next few examples we will demonstrate how to use Panel to quickly add some interactive controls to some object and make a simple app.
To see an overview of the different APIs Panel offers see the API user guide and for a quick reference for various Panel functionality see the overview.
Instead of editing code, it's much quicker and more straightforward to use sliders to adjust the values interactively. You can easily make a Panel app to explore a function's parameters using pn.interact
, which is similar to the ipywidgets interact function:
import panel as pn
pn.extension()
pn.interact(find_outliers)
As long as you have a live Python process running, dragging these widgets will trigger a call to the find_outliers
callback function, evaluating it for whatever combination of parameter values you select and displaying the results. A Panel like this makes it very easy to explore any function that produces a visual result of a supported type, such as Matplotlib (as above), Bokeh, Plotly, Altair, or various text and image types.
interact
is convenient, but what if you want more control over how it looks or works? First, let's see what interact
actually creates, by grabbing that object and displaying its representation:
kw = dict(window=(1, 60), variable=sorted(list(data.columns)), sigma=(1, 20))
i = pn.interact(find_outliers, **kw)
i.pprint()
As you can see, the interact
call created a pn.Column
object consisting of a WidgetBox (with 3 widgets) and a pn.Row
with one Matplotlib figure object. Panel is compositional, so you can mix and match these components any way you like, adding other objects as needed:
text = "<br>\n# Room Occupancy\nSelect the variable, and the time window for smoothing"
p = pn.Row(i[1][0], pn.Column(text, i[0][0], i[0][1]))
p
Note that the widgets stay linked to their plot even if they are in a different notebook cell:
i[0][2]
Also note that Panel widgets are reactive, so they will update even if you set the values by hand:
i[0][2].value = 5
You can use this compositional approach to combine different components such as widgets, plots, text, and other elements needed for an app or dashboard in arbitrary ways. The interact
example builds on a reactive programming model, where an input to the function changes and Panel reactively updates the output of the function. interact
is a convenient way to create widgets from the arguments to your function automatically, but Panel also provides a more explicit reactive API letting you specifically define connections between widgets and function arguments, and then lets you compose the resulting dashboard manually from scratch.
In the example below we explicitly declare each of the components of an app: widgets, a function to return the plot, column and row containers, and the completed occupancy
Panel app. Widget objects have multiple "parameters" (current value, allowed ranges, and so on), and here we will use Panel's depends
decorator to declare that function's input values should come from the widgets' value
parameters. Now when the function and the widgets are displayed, Panel will automatically update the displayed output whenever any of the inputs change:
import panel.widgets as pnw
variable = pnw.RadioButtonGroup(name='variable', value='Temperature',
options=list(data.columns))
window = pnw.IntSlider(name='window', value=10, start=1, end=60)
@pn.depends(variable, window)
def reactive_outliers(variable, window):
return find_outliers(variable, window, 10)
widgets = pn.Column("<br>\n# Room occupancy", variable, window)
occupancy = pn.Row(reactive_outliers, widgets)
occupancy
The above panels all work in the notebook cell (if you have a live Jupyter kernel running), but unlike other approaches such as ipywidgets, Panel apps work just the same in a standalone server. For instance, the app above can be launched as its own web server on your machine by uncommenting and running the following cell:
#occupancy.show()
Or, you can simply mark whatever you want to be in the separate web page with .servable()
, and then run the shell command panel serve --show Introduction.ipynb
to launch a server containing that object. (Here, we've also added a semicolon to avoid getting another copy of the occupancy app here in the notebook.)
occupancy.servable();
The above compositional approach is very flexible, but it ties your domain-specific code (the parts about sine waves) with your widget display code. That's fine for small, quick projects or projects dominated by visualization code, but what about large-scale, long-lived projects, where the code is used in many different contexts over time, such as in large batch runs, one-off command-line usage, notebooks, and deployed dashboards? For larger projects like that, it's important to be able to separate the parts of the code that are about the underlying domain (i.e. application or research area) from those that are tied to specific display technologies (such as Jupyter notebooks or web servers).
For such usages, Panel supports objects declared with the separate Param library, which provides a GUI-independent way of capturing and declaring the parameters of your objects (and dependencies between your code and those parameters), in a way that's independent of any particular application or dashboard technology. For instance, the above code can be captured in an object that declares the ranges and values of all parameters, as well as how to generate the plot, independently of the Panel library or any other way of interacting with the object:
import param
class RoomOccupancy(param.Parameterized):
variable = param.Selector(objects=list(data.columns))
window = param.Integer(default=10, bounds=(1, 20))
sigma = param.Number(default=10, bounds=(0, 20))
def view(self):
return find_outliers(self.variable, self.window, self.sigma)
obj = RoomOccupancy()
obj
The RoomOccupancy
class and the obj
instance have no dependency on Panel, Jupyter, or any other GUI or web toolkit; they simply declare facts about a certain domain (such as that smoothing requires window and sigma parameters, and that window is an integer greater than 0 and sigma is a positive real number). This information is then enough for Panel to create an editable and viewable representation for this object without having to specify anything that depends on the domain-specific details encapsulated in obj
:
pn.Row(obj.param, obj.view)
To support a particular domain, you can create hierarchies of such classes encapsulating all the parameters and functionality you need across different families of objects, with both parameters and code inheriting across the classes as appropriate, all without any dependency on a particular GUI library or even the presence of a GUI at all. This approach makes it practical to maintain a large codebase, all fully displayable and editable with Panel, in a way that can be maintained and adapted over time.
The above approaches each work with a very wide variety of displayable objects, including images, equations, tables, and plots. In each case, Panel provides interactive functionality using widgets and updates the displayed objects accordingly, while making very few assumptions about what actually is being displayed. Panel also supports richer, more dynamic interactivity where the displayed object is itself interactive, such as the JavaScript-based plots from Bokeh and Plotly.
For instance, if we substitute the Bokeh wrapper hvPlot for the Matplotlib wrapper provided with Pandas, we automatically get interactive plots that allow zooming, panning and hovering:
import hvplot.pandas
def hvplot(avg, highlight):
return avg.hvplot(height=200) * highlight.hvplot.scatter(color='orange', padding=0.1)
text2 = "## Room Occupancy\nSelect the variable and the smoothing values"
hvp = pn.interact(find_outliers, view_fn=hvplot, **kw)
pn.Column(pn.Row(pn.panel(text2, width=400), hvp[0]), hvp[1]).servable("Occupancy")
These interactive actions can be combined with more complex interactions with a plot (e.g. tap, hover) to make it easy to explore data more deeply and uncover connections. For instance, we can use HoloViews to make a more full-featured version of the hvPlot example that displays a table of the current measurement values at the hover position on the plot:
import holoviews as hv
tap = hv.streams.PointerX(x=data.index.min())
def hvplot2(avg, highlight):
line = avg.hvplot(height=300, width=500)
outliers = highlight.hvplot.scatter(color='orange', padding=0.1)
tap.source = line
return (line * outliers).opts(legend_position='top_right')
@pn.depends(tap.param.x)
def table(x):
index = np.abs((data.index - x).astype(int)).argmin()
return data.iloc[index]
app = pn.interact(find_outliers, view_fn=hvplot2, **kw)
pn.Row(
pn.Column("## Room Occupancy\nHover over the plot for more information.", app[0]),
pn.Row(app[1], table)
)
For a quick reference of different Panel functionality refer to the overview. If you want a more detailed description of different ways of using Panel, each appropriate for different applications see the following materials:
Just pick the style that seems most appropriate for the task you want to do, then study that section of the user guide. Regardless of which approach you take, you'll want to learn more about Panel's panes and layouts:
Finally, if you are building a complex multi-stage application, you can consider our support for organizing workflows consisting of multiple stages:
Or for more polished apps you can make use of Templates to achieve exactly the look and feel you want: