Vega-Altair: A declarative statistical visualization library for Python.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Interactive parameters and selections that enable dynamic, interactive visualizations with user input controls and cross-filtering. Parameters provide the foundation for creating responsive visualizations that update based on user interaction.
Core functions for creating interactive parameters that can be bound to UI controls or driven by selections.
def param(
name=None,
value=None,
bind=None,
empty=None,
expr=None,
**kwargs
):
"""
Create an interactive parameter.
Parameters:
- name: Parameter name (auto-generated if not provided)
- value: Initial parameter value
- bind: UI binding specification
- empty: Behavior when selection is empty
- expr: Expression for parameter value
Returns:
Parameter: Parameter object with operator methods
"""
class Parameter:
def __init__(self, **kwargs):
"""
Interactive parameter with logical operators.
Supports logical operations: &, |, ~, ==, !=, <, <=, >, >=
"""
def __and__(self, other):
"""Logical AND operation (param1 & param2)."""
def __or__(self, other):
"""Logical OR operation (param1 | param2)."""
def __invert__(self):
"""Logical NOT operation (~param)."""
def __eq__(self, other):
"""Equality comparison (param == value)."""
def __ne__(self, other):
"""Inequality comparison (param != value)."""
def __lt__(self, other):
"""Less than comparison (param < value)."""
def __le__(self, other):
"""Less than or equal (param <= value)."""
def __gt__(self, other):
"""Greater than comparison (param > value)."""
def __ge__(self, other):
"""Greater than or equal (param >= value)."""
def to_dict(self):
"""Convert parameter to dictionary specification."""Functions for creating different types of selections that capture user interactions.
def selection_point(
name=None,
fields=None,
on=None,
clear=None,
empty=None,
init=None,
nearest=None,
resolve=None,
toggle=None,
**kwargs
):
"""
Create a point selection parameter.
Parameters:
- name: Selection name
- fields: Data fields to project selection over
- on: Event specification for triggering selection
- clear: Event specification for clearing selection
- empty: Behavior when selection is empty ('all' or 'none')
- init: Initial selection values
- nearest: Whether to select nearest data point
- resolve: Selection resolution ('global', 'union', 'intersect')
- toggle: Toggle mode for selection ('true', 'false', or expression)
Returns:
SelectionParameter: Point selection parameter
"""
def selection_interval(
name=None,
encodings=None,
on=None,
clear=None,
empty=None,
init=None,
mark=None,
resolve=None,
translate=None,
zoom=None,
**kwargs
):
"""
Create an interval selection parameter.
Parameters:
- name: Selection name
- encodings: Encoding channels to project over ('x', 'y', etc.)
- on: Event specification for triggering selection
- clear: Event specification for clearing selection
- empty: Behavior when selection is empty
- init: Initial selection extent
- mark: Mark properties for selection brush
- resolve: Selection resolution
- translate: Translation interaction specification
- zoom: Zoom interaction specification
Returns:
SelectionParameter: Interval selection parameter
"""
# Legacy selection functions (deprecated but still available)
def selection_single(**kwargs):
"""Create single-point selection (deprecated, use selection_point)."""
def selection_multi(**kwargs):
"""Create multi-point selection (deprecated, use selection_point)."""Functions for binding parameters to UI controls for interactive input.
def binding(input_type, **kwargs):
"""
Create a general parameter binding specification.
Parameters:
- input_type: Type of input control
- **kwargs: Input-specific options
Returns:
dict: Binding specification
"""
def binding_checkbox(name=None, **kwargs):
"""
Create checkbox binding for boolean parameters.
Parameters:
- name: Input name/label
Returns:
dict: Checkbox binding specification
"""
def binding_radio(options, name=None, **kwargs):
"""
Create radio button binding for categorical parameters.
Parameters:
- options: List of option values
- name: Input name/label
Returns:
dict: Radio button binding specification
"""
def binding_range(
min=None,
max=None,
step=None,
name=None,
**kwargs
):
"""
Create range slider binding for numeric parameters.
Parameters:
- min: Minimum value
- max: Maximum value
- step: Step size
- name: Input name/label
Returns:
dict: Range slider binding specification
"""
def binding_select(options, name=None, **kwargs):
"""
Create select dropdown binding for categorical parameters.
Parameters:
- options: List of option values
- name: Input name/label
Returns:
dict: Select dropdown binding specification
"""Functions for creating conditional encodings and expressions based on parameters and selections.
def condition(
predicate,
if_true,
if_false=None,
**kwargs
):
"""
Create conditional encoding based on parameter or selection.
Parameters:
- predicate: Parameter, selection, or test expression
- if_true: Value when condition is true
- if_false: Value when condition is false (optional)
Returns:
dict: Conditional encoding specification
"""
def when(predicate):
"""
Start a conditional chain with when().then().otherwise().
Parameters:
- predicate: Parameter, selection, or test expression
Returns:
ChainedWhen: Object for method chaining
"""
class ChainedWhen:
def then(self, value):
"""
Specify value when condition is true.
Returns:
Then: Object for continuing chain
"""
class Then:
def when(self, predicate):
"""Add additional condition to chain."""
def otherwise(self, value):
"""Specify final fallback value."""Functions for creating value expressions and references.
def value(val):
"""
Create a value expression for fixed values in encodings.
Parameters:
- val: Fixed value (number, string, color, etc.)
Returns:
dict: Value specification
"""import altair as alt
# Numeric parameter with slider
size_param = alt.param(
value=100,
bind=alt.binding_range(min=10, max=500, step=10, name='Point Size')
)
chart = alt.Chart(data).add_params(
size_param
).mark_circle(size=size_param).encode(
x='x:Q',
y='y:Q'
)# Click selection with conditional color
click = alt.selection_point()
chart = alt.Chart(data).add_params(
click
).mark_circle().encode(
x='x:Q',
y='y:Q',
color=alt.condition(click, 'category:N', alt.value('lightgray'))
)# Brush selection for filtering
brush = alt.selection_interval()
base = alt.Chart(data).add_params(brush)
points = base.mark_circle().encode(
x='x:Q',
y='y:Q',
color=alt.condition(brush, 'category:N', alt.value('lightgray'))
)
bars = base.mark_bar().encode(
x='category:N',
y='count():Q'
).transform_filter(brush)
chart = points & bars# Dropdown parameter for category filtering
category_param = alt.param(
value='All',
bind=alt.binding_select(
options=['All', 'A', 'B', 'C'],
name='Category'
)
)
chart = alt.Chart(data).add_params(
category_param
).mark_point().encode(
x='x:Q',
y='y:Q',
color='category:N'
).transform_filter(
(category_param == 'All') | (alt.datum.category == category_param)
)# Multi-condition parameter
threshold_param = alt.param(value=50, bind=alt.binding_range(min=0, max=100))
chart = alt.Chart(data).add_params(
threshold_param
).mark_circle().encode(
x='x:Q',
y='y:Q',
color=alt.when(
alt.datum.value > threshold_param
).then(
alt.value('red')
).when(
alt.datum.value > threshold_param / 2
).then(
alt.value('orange')
).otherwise(
alt.value('blue')
)
)# Shared selection across multiple charts
brush = alt.selection_interval()
chart1 = alt.Chart(data).add_params(
brush
).mark_circle().encode(
x='x:Q',
y='y:Q',
color=alt.condition(brush, 'category:N', alt.value('lightgray'))
)
chart2 = alt.Chart(data).mark_bar().encode(
x='category:N',
y='mean(value):Q',
opacity=alt.condition(brush, alt.value(1.0), alt.value(0.3))
).transform_filter(brush)
combined = chart1 | chart2# Parameter with calculated expression
base_param = alt.param(value=10)
multiplier_param = alt.param(value=2)
# Use parameters in calculated field
chart = alt.Chart(data).add_params(
base_param,
multiplier_param
).mark_circle().encode(
x='x:Q',
y='y:Q',
size=alt.expr(f'{base_param} * {multiplier_param} * datum.value')
)from typing import Union, Dict, Any, Optional, List
# Parameter types
ParameterValue = Union[str, int, float, bool, List[Any]]
ParameterBinding = Dict[str, Any]
# Selection types
SelectionType = Union['point', 'interval']
SelectionResolution = Union['global', 'union', 'intersect']
SelectionEmpty = Union['all', 'none']
# Event specifications
EventType = Union[str, Dict[str, Any]]
EventStream = Union[str, Dict[str, Any]]
# Binding input types
InputType = Union['checkbox', 'radio', 'range', 'select', 'text', 'number', 'date', 'time', 'month', 'week', 'datetime-local', 'tel', 'url']
# Conditional predicate types
ConditionalPredicate = Union[Parameter, Dict[str, Any], str]
# Selection configuration
class SelectionConfig:
point: Optional[Dict[str, Any]] = None
interval: Optional[Dict[str, Any]] = None
# Parameter specification
class ParameterSpec:
name: str
value: Optional[ParameterValue] = None
bind: Optional[ParameterBinding] = None
expr: Optional[str] = None
# Selection parameter specification
class SelectionParameterSpec(ParameterSpec):
select: SelectionType
init: Optional[Dict[str, Any]] = None
on: Optional[EventStream] = None
clear: Optional[EventStream] = None
empty: Optional[SelectionEmpty] = None
resolve: Optional[SelectionResolution] = NoneInstall with Tessl CLI
npx tessl i tessl/pypi-altair