Welcome to Panel!
This section will get you set up with Panel and provide a basic overview of the features and strengths of Panel. The announcement blog is another great resource to learn about the features of Panel and get an idea of what it can do.
conda install -c pyviz panel
or using PyPI:
pip install panel
Support for classic Jupyter Notebook is included with Panel. If you want to work with JupyterLab, you will also need to install the optional PyViz JupyterLab extension:
conda install -c conda-forge jupyterlab jupyter labextension install @pyviz/jupyterlab_pyviz
Editor + Server¶
You can edit your Panel code as a .py file in any text editor, marking the objects you want to render as
.servable(), then launch a server with
panel serve my_script.py --show to open a browser tab showing your app or dashboard and backed by a live Python process.
JupyterLab and Classic notebook¶
In the classic Jupyter notebook environment and JupyterLab, first make sure to load the
pn.extension(). Panel objects will then render themselves if they are the last item in a notebook cell. For versions of
jupyterlab>=3.0 the necessary extension is automatically bundled in the
pyviz_comms package, which must be >=2.0. However note that for version of
jupyterlab<3.0 you must also manually install the JupyterLab extension with:
jupyter labextension install @pyviz/jupyterlab_pyviz
In Google Colaboratory, rendering for each notebook cell is isolated, which means that every cell must reload the Panel extension code separately. Panel can do this automatically when you first load the extension if you declare that you are running in Colab:
pn.extension(comms='colab'). Otherwise you will need to put
pn.extension() in each cell where you want to display Panel output. Either way, you should be able to have access to all of Panel’s functionality, though with a larger notebook size than with other notebook technologies that allow display code to be shared across cells.
Visual Studio Code (VSCode) versions 2020.4.74986 and later support ipywidgets, and Panel objects can be used as ipywidgets since Panel 0.10 thanks to
jupyter_bokeh, which means that you can now use Panel components interactively in VSCode. Ensure you install
pip install jupyter_bokeh or
conda install -c bokeh jupyter_bokeh and then enable the extension with
nteract and other ipywidgets notebooks¶
In other notebook environments that support rendering ipywidgets interactively, such as nteract, you can use the same underlying ipywidgets support as for vscode: Install
jupyter_bokeh and then use
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.
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.
Components of Panels¶
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()
Column  Column  Select(name='variable', options=['CO2', 'Humidity', ...], value='Temperature')  IntSlider(end=60, name='window', start=1, value=30)  IntSlider(end=20, name='sigma', start=1, value=10)  Row  Matplotlib(Figure, name='interactive02986')
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, pn.Column(text, i, i)) p
Note that the widgets stay linked to their plot even if they are in a different notebook cell:
Also note that Panel widgets are reactive, so they will update even if you set the values by hand:
i.value = 5
Composing new Panels¶
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
bind function 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) reactive_outliers = pn.bind(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:
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.)
During development, particularly when working with a raw script using
panel serve --show --autoreload can be very useful as the application will automatically update whenever the script or notebook or any of its imports change.
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
RoomOccupancy(name='RoomOccupancy03019', sigma=10, variable='Temperature', window=10)
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
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.
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:
APIs: An overview of the different APIs offered by Panel.
Interact: Instant GUI, given a function with arguments
Widgets: Explicitly instantiating widgets and linking them to actions
Parameters: Capturing parameters and their links to actions declaratively
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:
Components: An overview of the core components of Panel including Panes, Widgets and Layouts
Customization: How to set styles and sizes of Panel components
Deploy & Export: An overview on how to display, export and deploy Panel apps and dashboards
Finally, if you are building a complex multi-stage application, you can consider our support for organizing workflows consisting of multiple stages:
Pipelines: Making multi-stage processing pipelines in notebooks and as deployed apps
Or for more polished apps you can make use of Templates to achieve exactly the look and feel you want:
Templates: Composing one or more Panel objects into jinja2 template with full control over layout and styling.