In order to streamline and automate the creation and use of models that can be used for describing plots and scenes, Bokeh provides a collection of properties and property mixins. Property classes provide automatic validation and serialization for a large collection of useful types. Mixin and container classes provide for easy bulk addition of properties to model classes.
Provide property types for Bokeh models
Properties are objects that can be assigned as class attributes on Bokeh models, to provide automatic serialization, validation, and documentation.
This documentation is broken down into the following sections:
Overview
Basic Properties
Container Properties
DataSpec Properties
Helpers
Special Properties
Validation-only Properties
Validation Control
There are many property types defined in the module, for example Int to represent integral values, Seq to represent sequences (e.g. lists or tuples, etc.). Properties can also be combined: Seq(Float) represents a sequence of floating point values.
Int
Seq
Seq(Float)
For example, the following defines a model that has integer, string, and list[float] properties:
class SomeModel(Model): foo = Int bar = String(default="something") baz = List(Float, help="docs for baz prop")
As seen, properties can be declared as just the property type, e.g. foo = Int, in which case the properties are automatically instantiated on new Model objects. Or the property can be instantiated on the class, and configured with default values and help strings.
foo = Int
The properties of this class can be initialized by specifying keyword arguments to the initializer:
m = SomeModel(foo=10, bar="a str", baz=[1,2,3,4])
But also by setting the attributes on an instance:
m.foo = 20
Attempts to set a property to a value of the wrong type will result in a ValueError exception:
ValueError
>>> m.foo = 2.3 Traceback (most recent call last): << traceback omitted >> ValueError: expected a value of type Integral, got 2.3 of type float
Models with properties know how to serialize themselves, to be understood by BokehJS. Additionally, any help strings provided on properties can be easily and automatically extracted with the Sphinx extensions in the bokeh.sphinxext module.
Angle
Accept floating point angle values.
Angle is equivalent to Float but is provided for cases when it is more semantically meaningful.
Float
default (float or None, optional) – A default value for attributes created from this property to have (default: None)
help (str or None, optional) – A documentation string for this property. It will be automatically used by the bokeh_prop extension when generating Spinx documentation. (default: None)
serialized (bool, optional) – Whether attributes created from this property should be included in serialization (default: True)
readonly (bool, optional) – Whether attributes created from this property are read-only. (default: False)
Any
Accept all values.
The Any property does not do any validation or transformation.
default (obj or None, optional) – A default value for attributes created from this property to have (default: None)
Example
>>> class AnyModel(HasProps): ... prop = Any() ... >>> m = AnyModel() >>> m.prop = True >>> m.prop = 10 >>> m.prop = 3.14 >>> m.prop = "foo" >>> m.prop = [1, 2, 3]
AnyRef
Accept all values and force reference discovery.
Auto
Accepts only the string “auto”.
Useful for properties that can be configured to behave “automatically”.
This property is often most useful in conjunction with the Either property.
Either
>>> class AutoModel(HasProps): ... prop = Either(Float, Auto) ... >>> m = AutoModel() >>> m.prop = 10.2 >>> m.prop = "auto" >>> m.prop = "foo" # ValueError !! >>> m.prop = [1, 2, 3] # ValueError !!
Bool
Accept boolean values.
>>> class BoolModel(HasProps): ... prop = Bool(default=False) ... >>> m = BoolModel() >>> m.prop = True >>> m.prop = False >>> m.prop = 10 # ValueError !!
Byte
Accept integral byte values (0-255).
>>> class ByteModel(HasProps): ... prop = Byte(default=0) ... >>> m = ByteModel() >>> m.prop = 255 >>> m.prop = 256 # ValueError !! >>> m.prop = 10.3 # ValueError !!
Color
Accept color values in a variety of ways.
For colors, because we support named colors and hex values prefaced with a “#”, when we are handed a string value, there is a little interpretation: if the value is one of the 147 SVG named colors or it starts with a “#”, then it is interpreted as a value.
If a 3-tuple is provided, then it is treated as an RGB (0..255). If a 4-tuple is provided, then it is treated as an RGBa (0..255), with alpha as a float between 0 and 1. (This follows the HTML5 Canvas API.)
>>> class ColorModel(HasProps): ... prop = Color() ... >>> m = ColorModel() >>> m.prop = "firebrick" >>> m.prop = "#a240a2" >>> m.prop = (100, 100, 255) >>> m.prop = (100, 100, 255, 0.5) >>> m.prop = "junk" # ValueError !! >>> m.prop = (100.2, 57.3, 10.2) # ValueError !!
Complex
Accept complex floating point values.
default (complex or None, optional) – A default value for attributes created from this property to have (default: None)
DashPattern
Accept line dash specifications.
Express patterns that describe line dashes. DashPattern values can be specified in a variety of ways:
An enum: “solid”, “dashed”, “dotted”, “dotdash”, “dashdot”
a tuple or list of integers in the HTML5 Canvas dash specification style. Note that if the list of integers has an odd number of elements, then it is duplicated, and that duplicated list becomes the new dash list.
To indicate that dashing is turned off (solid lines), specify the empty list [].
Date
Accept Date (but not DateTime) values.
Datetime
Accept Datetime values.
Accept values according to a sequence of other property types.
Example:
>>> class EitherModel(HasProps): ... prop = Either(Bool, Int, Auto) ... >>> m = EitherModel() >>> m.prop = True >>> m.prop = 10 >>> m.prop = "auto" >>> m.prop = 10.3 # ValueError !! >>> m.prop = "foo" # ValueError !!
Enum
Accept values from enumerations.
The first value in enumeration is used as the default value, unless the default keyword argument is used.
default
See bokeh.core.enums for more information.
Accept floating point values.
>>> class FloatModel(HasProps): ... prop = Float() ... >>> m = FloatModel() >>> m.prop = 10 >>> m.prop = 10.3 >>> m.prop = "foo" # ValueError !!
FontSize
Image
Accept image file types, e.g PNG, JPEG, TIFF, etc.
This property can be configured with:
A string filename to be loaded with PIL.Image.open
PIL.Image.open
An RGB(A) NumPy array, will be converted to PNG
A PIL.Image.Image object
PIL.Image.Image
In all cases, the image data is serialized as a Base64 encoded string.
Instance
Accept values that are instances of HasProps.
HasProps
Accept signed integer values.
default (int or None, optional) – A default value for attributes created from this property to have (default: None)
>>> class IntModel(HasProps): ... prop = Int() ... >>> m = IntModel() >>> m.prop = 10 >>> m.prop = -200 >>> m.prop = 10.3 # ValueError !!
Interval
Accept numeric values that are contained within a given interval.
interval_type (numeric property) – numeric types for the range, e.g. Int, Float
start (number) – A minimum allowable value for the range. Values less than start will result in validation errors.
start
end (number) – A maximum allowable value for the range. Values greater than end will result in validation errors.
end
>>> class RangeModel(HasProps): ... prop = Range(Float, 10, 20) ... >>> m = RangeModel() >>> m.prop = 10 >>> m.prop = 20 >>> m.prop = 15 >>> m.prop = 2 # ValueError !! >>> m.prop = 22 # ValueError !! >>> m.prop = "foo" # ValueError !!
JSON
Accept JSON string values.
The value is transmitted and received by BokehJS as a string containing JSON content. i.e., you must use JSON.parse to unpack the value into a JavaScript hash.
JSON.parse
default (string or None, optional) – A default value for attributes created from this property to have (default: None)
MarkerType
MinMaxBounds
Accept (min, max) bounds tuples for use with Ranges.
Bounds are provided as a tuple of (min, max) so regardless of whether your range is increasing or decreasing, the first item should be the minimum value of the range and the second item should be the maximum. Setting min > max will result in a ValueError.
(min, max)
Setting bounds to None will allow your plot to pan/zoom as far as you want. If you only want to constrain one end of the plot, you can set min or max to None e.g. DataRange1d(bounds=(None, 12))
None
DataRange1d(bounds=(None, 12))
NonNegativeInt
Accept non-negative integers.
Percent
Accept floating point percentage values.
Percent can be useful and semantically meaningful for specifying things like alpha values and extents.
>>> class PercentModel(HasProps): ... prop = Percent() ... >>> m = PercentModel() >>> m.prop = 0.0 >>> m.prop = 0.2 >>> m.prop = 1.0 >>> m.prop = -2 # ValueError !! >>> m.prop = 5 # ValueError !!
PositiveInt
Accept positive integers.
RGB
Accept colors.RGB values.
Regex
Accept strings that match a given regular expression.
>>> class RegexModel(HasProps): ... prop = Regex("foo[0-9]+bar") ... >>> m = RegexModel() >>> m.prop = "foo123bar" >>> m.prop = "foo" # ValueError !! >>> m.prop = [1, 2, 3] # ValueError !!
Size
Accept non-negative numeric values.
>>> class SizeModel(HasProps): ... prop = Size() ... >>> m = SizeModel() >>> m.prop = 0 >>> m.prop = 10e6 >>> m.prop = -10 # ValueError !! >>> m.prop = "foo" # ValueError !!
String
Accept string values.
>>> class StringModel(HasProps): ... prop = String() ... >>> m = StringModel() >>> m.prop = "foo" >>> m.prop = 10.3 # ValueError !! >>> m.prop = [1, 2, 3] # ValueError !!
Struct
Accept values that are structures.
TimeDelta
Accept TimeDelta values.
Array
Accept NumPy array values.
ColumnData
Accept a Python dictionary suitable as the data attribute of a ColumnDataSource.
data
ColumnDataSource
This class is a specialization of Dict that handles efficiently encoding columns that are NumPy arrays.
Dict
Accept Python dict values.
If a default value is passed in, then a shallow copy of it will be used for each new use of this property.
List
Accept Python list values.
RelativeDelta
Accept RelativeDelta dicts for time delta values.
Accept non-string ordered sequences of values, e.g. list, tuple, array.
Tuple
Accept Python tuple values.
AngleSpec
A DataSpec property that accepts numeric fixed values, and also provides an associated units property to store angle units.
DataSpec
Acceptable values for units are "rad" and "deg".
"rad"
"deg"
ColorSpec
A DataSpec property that accepts Color fixed values.
The ColorSpec property attempts to first interpret string values as colors. Otherwise, string values are interpreted as field names. For example:
m.color = "#a4225f" # value (hex color string) m.color = "firebrick" # value (named CSS color string) m.color = "foo" # field (named "foo")
This automatic interpretation can be override using the dict format directly, or by using the field() function:
field()
m.color = { "field": "firebrick" } # field (named "firebrick") m.color = field("firebrick") # field (named "firebrick")
DataDistanceSpec
A DataSpec property that accepts numeric fixed values for data-space distances, and also provides an associated units property that reports "data" as the units.
"data"
Base class for properties that accept either a fixed value, or a string name that references a column in a ColumnDataSource.
Many Bokeh models have properties that a user might want to set either to a single fixed value, or to have the property take values from some column in a data source. As a concrete example consider a glyph with an x property for location. We might want to set all the glyphs that get drawn to have the same location, say x=10. It would be convenient to just be able to write:
x
x=10
glyph.x = 10
Alternatively, maybe the each glyph that gets drawn should have a different location, according to the “pressure” column of a data source. In this case we would like to be able to write:
glyph.x = "pressure"
Bokeh DataSpec properties (and subclasses) afford this ease of and consistency of expression. Ultimately, all DataSpec properties resolve to dictionary values, with either a "value" key, or a "field" key, depending on how it is set.
"value"
"field"
For instance:
glyph.x = 10 # => { 'value': 10 } glyph.x = "pressure" # => { 'field': 'pressure' }
When these underlying dictionary dictionary values are received in the browser, BokehJS knows how to interpret them and take the correct, expected action (i.e., draw the glyph at x=10, or draw the glyph with x coordinates from the “pressure” column). In this way, both use-cases may be expressed easily in python, without having to handle anything differently, from the user perspective.
It is worth noting that DataSpec properties can also be set directly with properly formed dictionary values:
glyph.x = { 'value': 10 } # same as glyph.x = 10 glyph.x = { 'field': 'pressure' } # same as glyph.x = "pressure"
Setting the property directly as a dict can be useful in certain situations. For instance some DataSpec subclasses also add a "units" key to the dictionary. This key is often set automatically, but the dictionary format provides a direct mechanism to override as necessary. Additionally, DataSpec can have a "transform" key, that specifies a client-side transform that should be applied to any fixed or field values before they are uses. As an example, you might want to apply a Jitter transform to the x values:
"units"
"transform"
Jitter
glyph.x = { 'value': 10, 'transform': Jitter(width=0.4) }
Note that DataSpec is not normally useful on its own. Typically, a model will define properties using one of the subclasses such as NumberSpec or ColorSpec. For example, a Bokeh model with x, y and color properties that can handle fixed values or columns automatically might look like:
NumberSpec
y
color
class SomeModel(Model): x = NumberSpec(default=0, help="docs for x") y = NumberSpec(default=0, help="docs for y") color = ColorSpec(help="docs for color") # defaults to None
DistanceSpec
A DataSpec property that accepts numeric fixed values or strings that refer to columns in a ColumnDataSource, and also provides an associated units property to store units information. Acceptable values for units are "screen" and "data".
"screen"
FontSizeSpec
A DataSpec property that accepts font-size fixed values.
The FontSizeSpec property attempts to first interpret string values as font sizes (i.e. valid CSS length values). Otherwise string values are interpreted as field names. For example:
m.font_size = "13px" # value m.font_size = "1.5em" # value m.font_size = "foo" # field
A full list of all valid CSS length units can be found here:
https://drafts.csswg.org/css-values/#lengths
MarkerSpec
A DataSpec property that accepts marker types as fixed values.
The MarkerSpec property attempts to first interpret string values as marker types. Otherwise string values are interpreted as field names. For example:
m.font_size = "circle" # value m.font_size = "square" # value m.font_size = "foo" # field
A DataSpec property that accepts numeric and datetime fixed values.
By default, date and datetime values are immediately converted to milliseconds since epoch. It is possible to disable processing of datetime values by passing accept_datetime=False.
accept_datetime=False
By default, timedelta values are immediately converted to absolute milliseconds. It is possible to disable processing of timedelta values by passing accept_timedelta=False
accept_timedelta=False
Timedelta values are interpreted as absolute milliseconds.
m.location = 10.3 # value m.location = "foo" # field
PropertyUnitsSpec
A DataSpec property that accepts numeric fixed values, and also provides an associated units property to store units information.
ScreenDistanceSpec
A DataSpec property that accepts numeric fixed values for screen-space distances, and also provides an associated units property that reports "screen" as the units.
StringSpec
A DataSpec property that accepts string fixed values.
Because acceptable fixed values and field names are both strings, it can be necessary explicitly to disambiguate these possibilities. By default, string values are interpreted as fields, but the value() function can be used to specify that a string should interpreted as a value:
value()
m.title = value("foo") # value m.title = "foo" # field
UnitsSpec
A DataSpec property that accepts numeric fixed values, and also serializes associated units values.
expr
Convenience function to explicitly return an “expr” specification for a Bokeh DataSpec property.
expression (Expression) – a computed expression for a DataSpec property.
transform (Transform, optional) – a transform to apply (default: None)
{ "expr": expression }
dict
Note
This function is included for completeness. String values for property specifications are by default interpreted as field names.
field
Convenience function to explicitly return a “field” specification for a Bokeh DataSpec property.
name (str) – name of a data source field to reference for a DataSpec property.
{ "field": name }
value
Convenience function to explicitly return a “value” specification for a Bokeh DataSpec property.
val (any) – a fixed value to specify for a DataSpec property.
{ "value": name }
String values for property specifications are by default interpreted as field names. This function is especially useful when you want to specify a fixed value with text properties.
# The following will take text values to render from a data source # column "text_column", but use a fixed value "16px" for font size p.text("x", "y", text="text_column", text_font_size=value("16px"), source=source)
Include
Include “mix-in” property collection in a Bokeh model.
See bokeh.core.property_mixins for more details.
Override
Override attributes of Bokeh property in derived Models.
When subclassing a Bokeh Model, it may be desirable to change some of the attributes of the property itself, from those on the base class. This is accomplished using the Override class.
Currently, Override can only be use to override the default value for the property.
default (obj) – a default value for this property on a subclass
Consider the following class definitions:
from bokeh.model import Model from bokeh.properties import Int, Override class Parent(Model): foo = Int(default=10) class Child(Parent): foo = Override(default=20)
The parent class has an integer property foo with default value 10. The child class uses the following code:
foo
foo = Override(default=20)
to specify that the default value for the foo property should be 20 on instances of the child class:
>>> p = Parent() >>> p.foo 10 >>> c = Child() >>> c.foo 20
PandasDataFrame
Accept Pandas DataFrame values.
This property only exists to support type validation, e.g. for “accepts” clauses. It is not serializable itself, and is not useful to add to Bokeh models directly.
PandasGroupBy
By default, Bokeh properties perform type validation on values. This helps to ensure the consistency of any data exchanged between Python and JavaScript, as well as provide detailed and immediate feedback to users if they attempt to set values of the wrong type. However, these type checks incur some overhead. In some cases it may be desirable to turn off validation in specific places, or even entirely, in order to boost performance. The following API is available to control when type validation occurs.
validate
Control validation of bokeh properties
This can be used as a context manager, or as a normal callable
value (bool) – Whether validation should occur or not
with validate(False): # do no validate while within this block pass validate(False) # don't validate ever
See also
validation_on(): check the state of validation
validation_on()
without_property_validation(): function decorator
without_property_validation()
without_property_validation
Turn off property validation during update callbacks
@without_property_validation def update(attr, old, new): # do things without validation
validate: context mangager for more fine-grained control