Skip to content

How to use filters

This guide shows you how to add filters to your dashboard. A filter selects a subset of rows of a component's data to alter the appearance of that component. The following components are reactive to filters:

It is possible to add filters to a page or container. Both the Page model and the Container model have an optional controls argument where you can give any number of controls, including filters. A filter uses the Filter model to filter the data_frame of the figure function of a target component model such as Graph.

When the dashboard is running there are two ways for a user to set a filter:

By default, filters that control components with dynamic data are dynamically updated when the underlying data changes while the dashboard is running.

Basic filters

To add a filter to your page, do the following:

  1. add the Filter model into the controls argument of the Page model
  2. configure the column argument, which denotes the target column to be filtered

You can also set targets to specify which components on the page the filter should apply to. If this is not explicitly set then targets defaults to all components on the page whose data source includes column. You can additionally include another control's id in targets to keep multiple controls in sync.

Basic Filter

from vizro import Vizro
import vizro.plotly.express as px
import vizro.models as vm

iris = px.data.iris()

page = vm.Page(
    title="My first page",
    components=[
        vm.Graph(figure=px.scatter(iris, x="sepal_length", y="petal_width", color="species")),
    ],
    controls=[
        vm.Filter(column="species"),
    ],
)

dashboard = vm.Dashboard(pages=[page])
Vizro().build(dashboard).run()

Run and edit this code in Py.Cafe

# Still requires a .py to add data to the data manager and parse YAML configuration
# See yaml_version example
pages:
  - components:
      - figure:
          _target_: scatter
          data_frame: iris
          x: sepal_length
          y: petal_width
          color: species
        type: graph
    controls:
      - column: species
        type: filter
    title: My first page

The dashboard renders the "Basic Filter" example.

Filter

The selector is configured automatically based on the target column type data as follows:

  • Categorical data uses vm.Dropdown(multi=True) where options is the set of unique values found in column across all the data sources of components in targets.
  • Numerical data uses vm.Slider(range=True) where min and max are the overall minimum and maximum values found in column across all the data sources of components in targets.
  • Temporal data (date or datetime columns) uses vm.DatePicker(range=True) where min and max are the overall minimum and maximum values found in column across all the data sources of components in targets. A column can be converted to this type with pandas.to_datetime. For time columns (containing datetime.time objects), vm.TimePicker(range=True) is used instead; a column can be converted to this type with pandas.to_datetime followed by .time (for example, df["t"] = pd.to_datetime(df["t"]).time). To filter a datetime column by both date and time, pass vm.DateTimePicker as the selector explicitly.
  • Boolean data uses vm.Switch which provides a toggle interface for True/False values. The Switch also works with binary numerical columns containing 0/1 values.

The following example demonstrates these default selector types.

Default Filter selectors

import pandas as pd
from vizro import Vizro
import vizro.plotly.express as px
import vizro.models as vm

df_stocks = px.data.stocks(datetimes=True)

df_stocks_long = pd.melt(
    df_stocks,
    id_vars='date',
    value_vars=['GOOG', 'AAPL', 'AMZN', 'FB', 'NFLX', 'MSFT'],
    var_name='stocks',
    value_name='value'
)

df_stocks_long['value'] = df_stocks_long['value'].round(3)
df_stocks_long['Is GOOG?'] = df_stocks_long["stocks"] == "GOOG"

page = vm.Page(
    title="My first page",
    components=[
        vm.Graph(figure=px.line(df_stocks_long, x="date", y="value", color="stocks")),
    ],
    controls=[
        vm.Filter(column="stocks"),
        vm.Filter(column="value"),
        vm.Filter(column="date"),
        vm.Filter(column="Is GOOG?"),
    ],
)

dashboard = vm.Dashboard(pages=[page])
Vizro().build(dashboard).run()

Run and edit this code in Py.Cafe

# Still requires a .py to add data to the data manager and parse YAML configuration
# See yaml_version example
pages:
  - components:
      - figure:
          _target_: line
          data_frame: df_stocks_long
          x: date
          y: value
          color: stocks
        type: graph
    controls:
      - column: stocks
        type: filter
      - column: value
        type: filter
      - column: date
        type: filter
      - column: Is GOOG?
        type: filter
    title: My first page

The dashboard renders the "Default Filter selectors" example.

FilterDefault

Hierarchical filters

A hierarchical filter is a filter where the user chooses values from a tree of grouped values. For example, cities around the world could be grouped into a hierarchy by continent and then by country. Rows of the data are filtered down to the finest-grained (most "zoomed in") level (the leaves of the tree). In the continent/country/city example, this would be city.

By default (path mode), each selection is matched by its full path through the tree, so the same leaf label appearing under different branches (for example a city name shared by two countries) is filtered independently; clearing a multi-select path-mode filter (removing every selection) then matches no rows, because there is no path left to filter on. If you set full_path=False on the Cascader selector (leaf mode), rows are instead matched on the finest-grained column alone, so a hierarchical filter behaves like a flat filter on the leaf column and leaf labels must be unique across the tree. See hierarchical selectors for how to choose between the two modes.

To add a hierarchical filter to your page:

  1. add a Filter to controls, the same as for a basic filter
  2. set column to a list of at least two columns' names from the top level of the hierarchy down to the column you want to filter on

Path mode (full_path=True, the default) constraints

  • The number of columns in Filter.column must equal the number of levels in the options hierarchy, because every level of a selected path is matched against the corresponding column. (Leaf mode has no such restriction: it matches on the last column only, so options may be arbitrarily deep.)
  • Path mode does not support set_controls yet, because a single click cannot reconstruct a full root-to-leaf path. Use leaf mode (full_path=False) for filters that are targets of set_controls.

Hierarchical Filter

from vizro import Vizro
import vizro.plotly.express as px
import vizro.models as vm

gapminder = px.data.gapminder().query("year == 2007")

page = vm.Page(
    title="Gapminder 2007",
    components=[
        vm.Graph(
            figure=px.scatter(
                gapminder,
                x="gdpPercap",
                y="lifeExp",
                size="pop",
                hover_name="country",
                color="continent",
            )
        ),
    ],
    controls=[vm.Filter(column=["continent", "country"])],
)

dashboard = vm.Dashboard(pages=[page])
Vizro().build(dashboard).run()

Run and edit this code in Py.Cafe

# Still requires a .py to add data to the data manager and parse YAML configuration
# See yaml_version example
pages:
  - components:
      - figure:
          _target_: scatter
          data_frame: gapminder
          x: gdpPercap
          y: lifeExp
          size: pop
          color: continent
          hover_name: country
        type: graph
    controls:
      - column:
          - continent
          - country
        type: filter
    title: Gapminder 2007

The dashboard renders the "Hierarchical Filter" example.

Change selector

Use a different selector argument for the Filter model for a different selector model. For a single column string, available selectors are Checklist, Dropdown, RadioItems, Slider, DatePicker, TimePicker, DateTimePicker and Switch. For a hierarchical filter (column as a list), use Cascader as in the section above.

You can explore and test all available selectors interactively on our feature demo dashboard.

Filter with different selector

from vizro import Vizro
import vizro.plotly.express as px
import vizro.models as vm

iris = px.data.iris()

page = vm.Page(
    title="My first page",
    components=[
        vm.Graph(figure=px.scatter(iris, x="sepal_length", y="petal_width")),
    ],
    controls=[
        vm.Filter(column="species", selector=vm.RadioItems()),
    ],
)

dashboard = vm.Dashboard(pages=[page])
Vizro().build(dashboard).run()

Run and edit this code in Py.Cafe

# Still requires a .py to add data to the data manager and parse YAML configuration
# See yaml_version example
pages:
  - components:
      - figure:
          _target_: scatter
          data_frame: iris
          x: sepal_length
          y: petal_width
        type: graph
    controls:
      - column: species
        selector:
          type: radio_items
        type: filter
    title: My first page

The dashboard renders the "Filter with different selector" example.

Selector

Further customization

For further customizations, refer to the guide to selectors and the Filter model. Some popular choices are:

  • Select which components the filter applies to by using targets.
  • Customize the selector, for example multi to switch between a multi-option and single-option selector, options for a categorical filter or min and max for a numerical filter.
  • Make the filter's selector invisible by setting visible=False.
  • Stop the filter from applying as soon as its value changes by setting its selector's actions=None, then apply it on demand with a button. See apply controls with a button.

Below is an example where we only target one page component, and where we further customize the chosen selector.

Customized Filter

from vizro import Vizro
import vizro.plotly.express as px
import vizro.models as vm

iris = px.data.iris()

page = vm.Page(
    title="My first page",
    components=[
        vm.Graph(id="scatter_chart", figure=px.scatter(iris, x="sepal_length", y="petal_width", color="species")),
        vm.Graph(figure=px.scatter(iris, x="petal_length", y="sepal_width", color="species")),
    ],
    controls=[
        vm.Filter(column="petal_length",targets=["scatter_chart"], selector=vm.Slider(range=True, step=1)),
    ],
)

dashboard = vm.Dashboard(pages=[page])
Vizro().build(dashboard).run()

Run and edit this code in Py.Cafe

# Still requires a .py to add data to the data manager and parse YAML configuration
# See yaml_version example
pages:
  - components:
      - figure:
          _target_: scatter
          data_frame: iris
          x: sepal_length
          y: petal_width
          color: species
        id: scatter_chart
        type: graph
      - figure:
          _target_: scatter
          data_frame: iris
          x: petal_length
          y: sepal_width
          color: species
        type: graph
    controls:
      - column: petal_length
        targets:
          - scatter_chart
        selector:
          step: 1
          type: slider
          range: true
        type: filter
    title: My first page

The dashboard renders the "Customized Filter" example.

Advanced