holoviews.util Package#
util
Package#
- class holoviews.util.Dynamic(*, kwargs, link_dataset, link_inputs, operation, shared_data, streams, name)[source]#
Bases:
ParameterizedFunction
Dynamically applies a callable to the Elements in any HoloViews object. Will return a DynamicMap wrapping the original map object, which will lazily evaluate when a key is requested. By default Dynamic applies a no-op, making it useful for converting HoloMaps to a DynamicMap.
Any supplied kwargs will be passed to the callable and any streams will be instantiated on the returned DynamicMap. If the supplied operation is a method on a parameterized object which was decorated with parameter dependencies Dynamic will automatically create a stream to watch the parameter changes. This default behavior may be disabled by setting watch=False.
operation
= param.Callable(allow_refs=False, label=’Operation’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x304d29410>)Operation or user-defined callable to apply dynamically
kwargs
= param.Dict(allow_refs=False, class_=<class ‘dict’>, default={}, label=’Kwargs’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x304d31bd0>)Keyword arguments passed to the function.
link_inputs
= param.Boolean(allow_refs=False, default=True, label=’Link inputs’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x30454bf10>)If Dynamic is applied to another DynamicMap, determines whether linked streams and links attached to its Callable inputs are transferred to the output of the utility. For example if the Dynamic utility is applied to a DynamicMap with an RangeXY, this switch determines whether the corresponding visualization should update this stream with range changes originating from the newly generated axes.
link_dataset
= param.Boolean(allow_refs=False, default=True, label=’Link dataset’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x304e09190>)Determines whether the output of the operation should inherit the .dataset property of the input to the operation. Helpful for tracking data providence for user supplied functions, which do not make use of the clone method. Should be disabled for operations where the output is not derived from the input and instead depends on some external state.
shared_data
= param.Boolean(allow_refs=False, default=False, label=’Shared data’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x3049af6d0>)Whether the cloned DynamicMap will share the same cache.
streams
= param.ClassSelector(allow_refs=False, class_=(<class ‘list’>, <class ‘dict’>), default=[], label=’Streams’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x3047bb850>)List of streams to attach to the returned DynamicMap
- class holoviews.util.OptsMeta(name, bases, dict_)[source]#
Bases:
ParameterizedMetaclass
Improve error message when running something like: ‘hv.opts.Curve()’ without a plotting backend.
- property abstract#
Return True if the class has an attribute __abstract set to True. Subclasses will return False unless they themselves have __abstract set to true. This mechanism allows a class to declare itself to be abstract (e.g. to avoid it being offered as an option in a GUI), without the “abstract” property being inherited by its subclasses (at least one of which is presumably not abstract).
- get_param_descriptor(param_name)[source]#
Goes up the class hierarchy (starting from the current class) looking for a Parameter class attribute param_name. As soon as one is found as a class attribute, that Parameter is returned along with the class in which it is declared.
- mro()#
Return a type’s method resolution order.
- holoviews.util.examples(path='holoviews-examples', verbose=False, force=False, root='/Users/runner/work/holoviews/holoviews/holoviews/util/__init__.py')[source]#
Copies the notebooks to the supplied path.
- class holoviews.util.extension(*, name)[source]#
Bases:
extension
Helper utility used to load holoviews extensions. These can be plotting extensions, element extensions or anything else that can be registered to work with HoloViews.
The plotting extension is the most commonly used and is used to select the plotting backend. The plotting extension can be loaded using the backend name, e.g. ‘bokeh’, ‘matplotlib’ or ‘plotly’.
Examples#
Activate the bokeh plotting extension:
`python import holoviews as hv hv.extension("bokeh") `
- class holoviews.util.opts(*args, **params)[source]#
Bases:
ParameterizedFunction
Utility function to set options at the global level or to provide an Options object that can be used with the .options method of an element or container.
Option objects can be generated and validated in a tab-completable way (in appropriate environments such as Jupyter notebooks) using completers such as opts.Curve, opts.Image, opts.Overlay, etc.
To set opts globally you can pass these option objects into opts.defaults:
opts.defaults(*options)
For instance:
opts.defaults(opts.Curve(color=’red’))
To set opts on a specific object, you can supply these option objects to the .options method.
For instance:
curve = hv.Curve([1,2,3]) curve.options(opts.Curve(color=’red’))
The options method also accepts lists of Option objects.
strict
= param.Boolean(allow_refs=False, default=False, label=’Strict’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x305a63bd0>)Whether to be strict about the options specification. If not set to strict (default), any invalid keywords are simply skipped. If strict, invalid keywords prevent the options being applied.
- classmethod apply_groups(obj, options=None, backend=None, clone=True, **kwargs)[source]#
Applies nested options definition grouped by type.
Applies options on an object or nested group of objects, returning a new object with the options applied. This method accepts the separate option namespaces explicitly (i.e. ‘plot’, ‘style’, and ‘norm’).
If the options are to be set directly on the object a simple format may be used, e.g.:
- opts.apply_groups(obj, style={‘cmap’: ‘viridis’},
plot={‘show_title’: False})
If the object is nested the options must be qualified using a type[.group][.label] specification, e.g.:
- opts.apply_groups(obj, {‘Image’: {‘plot’: {‘show_title’: False},
‘style’: {‘cmap’: ‘viridis}}})
If no opts are supplied all options on the object will be reset.
- Args:
- options (dict): Options specification
Options specification should be indexed by type[.group][.label] or option type (‘plot’, ‘style’, ‘norm’).
- backend (optional): Backend to apply options to
Defaults to current selected backend
- clone (bool, optional): Whether to clone object
Options can be applied inplace with clone=False
- **kwargs: Keywords of options by type
Applies options directly to the object by type (e.g. ‘plot’, ‘style’, ‘norm’) specified as dictionaries.
- Returns:
Returns the object or a clone with the options applied
- class holoviews.util.output(*args, **params)[source]#
Bases:
ParameterizedFunction
Helper used to set HoloViews display options. Arguments are supplied as a series of keywords in any order:
backend : The backend used by HoloViews fig : The static figure format holomap : The display type for holomaps widgets : The widget mode for widgets fps : The frames per second used for animations max_frames : The max number of frames rendered (default 500) size : The percentage size of displayed output dpi : The rendered dpi of the figure filename : The filename of the saved output, if any (default None) info : The information to page about the displayed objects (default False) css : Optional css style attributes to apply to the figure image tag widget_location : The position of the widgets relative to the plot
- holoviews.util.render(obj, backend=None, **kwargs)[source]#
Renders the HoloViews object to the corresponding object in the specified backend, e.g. a Matplotlib or Bokeh figure.
The backend defaults to the currently declared default backend. The resulting object can then be used with other objects in the specified backend. For instance, if you want to make a multi-part Bokeh figure using a plot type only available in HoloViews, you can use this function to return a Bokeh figure that you can use like any hand-constructed Bokeh figure in a Bokeh layout.
Arguments#
- obj: HoloViews object
The HoloViews object to render
- backend: string
A valid HoloViews rendering backend
- **kwargs: dict
Additional keyword arguments passed to the renderer, e.g. fps for animations
Returns#
- rendered:
The rendered representation of the HoloViews object, e.g. if backend=’matplotlib’ a matplotlib Figure or FuncAnimation
- holoviews.util.renderer(name)[source]#
Helper utility to access the active renderer for a given extension.
- holoviews.util.save(obj, filename, fmt='auto', backend=None, resources='cdn', toolbar=None, title=None, **kwargs)[source]#
Saves the supplied object to file.
The available output formats depend on the backend being used. By default and if the filename is a string the output format will be inferred from the file extension. Otherwise an explicit format will need to be specified. For ambiguous file extensions such as html it may be necessary to specify an explicit fmt to override the default, e.g. in the case of ‘html’ output the widgets will default to fmt=’widgets’, which may be changed to scrubber widgets using fmt=’scrubber’.
Arguments#
- obj: HoloViews object
The HoloViews object to save to file
- filename: string or IO object
The filename or BytesIO/StringIO object to save to
- fmt: string
The format to save the object as, e.g. png, svg, html, or gif and if widgets are desired either ‘widgets’ or ‘scrubber’
- backend: string
A valid HoloViews rendering backend, e.g. bokeh or matplotlib
- resources: string or bokeh.resource.Resources
Bokeh resources used to load bokehJS components. Defaults to CDN, to embed resources inline for offline usage use ‘inline’ or bokeh.resources.INLINE.
- toolbar: bool or None
Whether to include toolbars in the exported plot. If None, display the toolbar unless fmt is png and backend is bokeh. If True, always include the toolbar. If False, do not include the toolbar.
- title: string
Custom title for exported HTML file
- **kwargs: dict
Additional keyword arguments passed to the renderer, e.g. fps for animations
_versions
Module#
command
Module#
python -m holoviews.util.command Conversion_Example.ipynb OR holoviews Conversion_Example.ipynb
locator
Module#
Minimal set of functionality of Matplotlib’s MaxNLocator to choose contour levels without having to have Matplotlib installed. Taken from Matplotlib 3.8.0.
- holoviews.util.locator.nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True)[source]#
Modify the endpoints of a range as needed to avoid singularities.
Parameters#
- vmin, vmaxfloat
The initial endpoints.
- expanderfloat, default: 0.001
Fractional amount by which vmin and vmax are expanded if the original interval is too small, based on tiny.
- tinyfloat, default: 1e-15
Threshold for the ratio of the interval to the maximum absolute value of its endpoints. If the interval is smaller than this, it will be expanded. This value should be around 1e-15 or larger; otherwise the interval will be approaching the double precision resolution limit.
- increasingbool, default: True
If True, swap vmin, vmax if vmin > vmax.
Returns#
- vmin, vmaxfloat
Endpoints, expanded and/or swapped if necessary. If either input is inf or NaN, or if both inputs are 0 or very close to zero, it returns -expander, expander.
parser
Module#
The magics offered by the HoloViews IPython extension are powerful and support rich, compositional specifications. To avoid the the brittle, convoluted code that results from trying to support the syntax in pure Python, this file defines suitable parsers using pyparsing that are cleaner and easier to understand.
Pyparsing is required by matplotlib and will therefore be available if HoloViews is being used in conjunction with matplotlib.
- class holoviews.util.parser.CompositorSpec[source]#
Bases:
Parser
The syntax for defining a set of compositor is as follows:
[ mode op(spec) [settings] value ]+
The components are:
mode : Operation mode, either ‘data’ or ‘display’. group : Value identifier with capitalized initial letter. op : The name of the operation to apply. spec : Overlay specification of form (A * B) where A and B are
dotted path specifications.
- settingsOptional list of keyword arguments to be used as
parameters to the operation (in square brackets).
- classmethod collect_tokens(parseresult, mode)[source]#
Collect the tokens from a (potentially) nested parse result.
- class holoviews.util.parser.OptsSpec[source]#
Bases:
Parser
An OptsSpec is a string specification that describes an OptionTree. It is a list of tree path specifications (using dotted syntax) separated by keyword lists for any of the style, plotting or normalization options. These keyword lists are denoted ‘plot(..)’, ‘style(…)’ and ‘norm(…)’ respectively. These three groups may be specified even more concisely using keyword lists delimited by square brackets, parentheses and braces respectively. All these sets are optional and may be supplied in any order.
For instance, the following string:
Image (interpolation=None) plot(show_title=False) Curve style(color=’r’)
Would specify an OptionTree where Image has “interpolation=None” for style and ‘show_title=False’ for plot options. The Curve has a style set such that color=’r’.
The parser is fairly forgiving; commas between keywords are optional and additional spaces are often allowed. The only restriction is that keywords must be immediately followed by the ‘=’ sign (no space).
- classmethod apply_deprecations(path)[source]#
Convert any potentially deprecated paths and issue appropriate warnings
- classmethod collect_tokens(parseresult, mode)[source]#
Collect the tokens from a (potentially) nested parse result.
- classmethod parse(line, ns=None)[source]#
Parse an options specification, returning a dictionary with path keys and {‘plot’:<options>, ‘style’:<options>} values.
- classmethod parse_options(line, ns=None)[source]#
Similar to parse but returns a list of Options objects instead of the dictionary format.
settings
Module#
- class holoviews.util.settings.KeywordSettings[source]#
Bases:
object
Base class for options settings used to specified collections of keyword options.
- classmethod extract_keywords(line, items)[source]#
Given the keyword string, parse a dictionary of options.
- class holoviews.util.settings.OutputSettings[source]#
Bases:
KeywordSettings
Class for controlling display and output settings.
- classmethod extract_keywords(line, items)[source]#
Given the keyword string, parse a dictionary of options.
transform
Module#
- class holoviews.util.transform.df_dim(obj, *args, **kwargs)[source]#
Bases:
dim
A subclass of dim which provides access to the DataFrame namespace along with tab-completion and type coercion allowing the expression to be applied on any columnar dataset.
- applies(dataset, strict=False)[source]#
Determines whether the dim transform can be applied to the Dataset, i.e. whether all referenced dimensions can be resolved.
- apply(dataset, flat=False, expanded=None, ranges=None, all_values=False, keep_index=False, compute=True, strict=False)[source]#
Evaluates the transform on the supplied dataset.
- Args:
dataset: Dataset object to evaluate the expression on flat: Whether to flatten the returned array expanded: Whether to use the expanded expand values ranges: Dictionary for ranges for normalization all_values: Whether to evaluate on all values
Whether to evaluate on all available values, for some element types, such as Graphs, this may include values not included in the referenced column
- keep_index: For data types that support indexes, whether the index
should be preserved in the result.
- compute: For data types that support lazy evaluation, whether
the result should be computed before it is returned.
- strict: Whether to strictly check for dimension matches
(if False, counts any dimensions with matching names as the same)
- Returns:
values: NumPy array computed by evaluating the expression
- bin(bins, labels=None)[source]#
Bins continuous values.
Bins continuous using the provided bins and assigns labels either computed from each bins center point or from the supplied labels.
- Args:
bins: List or array containing the bin boundaries labels: List of labels to assign to each bin
If the bins are length N the labels should be length N-1
- categorize(categories, default=None)[source]#
Replaces discrete values with supplied categories
Replaces discrete values in input array into a fixed set of categories defined either as a list or dictionary.
- Args:
categories: List or dict of categories to map inputs to default: Default value to assign if value not in categories
- clone(dimension=None, ops=None, dim_type=None)[source]#
Creates a clone of the dim expression optionally overriding the dim and ops.
- lognorm(limits=None)[source]#
- Unity-based normalization log scale.
Apply the same transformation as matplotlib.colors.LogNorm
- Args:
limits: tuple of (min, max) defining the normalization range
- norm(limits=None)[source]#
Unity-based normalization to scale data into 0-1 range.
(values - min) / (max - min)
- Args:
limits: tuple of (min, max) defining the normalization range
- classmethod pipe(func, *args, **kwargs)[source]#
Wrapper to give multidimensional transforms a more intuitive syntax. For a custom function ‘func’ with signature (*args, **kwargs), call as dim.pipe(func, *args, **kwargs).
- classmethod register(key, function)[source]#
Register a custom dim transform function which can from then on be referenced by the key.
- property str#
Casts values to strings or provides str accessor.
- class holoviews.util.transform.dim(obj, *args, **kwargs)[source]#
Bases:
object
dim transform objects are a way to express deferred transforms on Datasets. dim transforms support all mathematical and bitwise operators, NumPy ufuncs and methods, and provide a number of useful methods for normalizing, binning and categorizing data.
- applies(dataset, strict=False)[source]#
Determines whether the dim transform can be applied to the Dataset, i.e. whether all referenced dimensions can be resolved.
- apply(dataset, flat=False, expanded=None, ranges=None, all_values=False, keep_index=False, compute=True, strict=False)[source]#
Evaluates the transform on the supplied dataset.
- Args:
dataset: Dataset object to evaluate the expression on flat: Whether to flatten the returned array expanded: Whether to use the expanded expand values ranges: Dictionary for ranges for normalization all_values: Whether to evaluate on all values
Whether to evaluate on all available values, for some element types, such as Graphs, this may include values not included in the referenced column
- keep_index: For data types that support indexes, whether the index
should be preserved in the result.
- compute: For data types that support lazy evaluation, whether
the result should be computed before it is returned.
- strict: Whether to strictly check for dimension matches
(if False, counts any dimensions with matching names as the same)
- Returns:
values: NumPy array computed by evaluating the expression
- bin(bins, labels=None)[source]#
Bins continuous values.
Bins continuous using the provided bins and assigns labels either computed from each bins center point or from the supplied labels.
- Args:
bins: List or array containing the bin boundaries labels: List of labels to assign to each bin
If the bins are length N the labels should be length N-1
- categorize(categories, default=None)[source]#
Replaces discrete values with supplied categories
Replaces discrete values in input array into a fixed set of categories defined either as a list or dictionary.
- Args:
categories: List or dict of categories to map inputs to default: Default value to assign if value not in categories
- clone(dimension=None, ops=None, dim_type=None)[source]#
Creates a clone of the dim expression optionally overriding the dim and ops.
- lognorm(limits=None)[source]#
- Unity-based normalization log scale.
Apply the same transformation as matplotlib.colors.LogNorm
- Args:
limits: tuple of (min, max) defining the normalization range
- norm(limits=None)[source]#
Unity-based normalization to scale data into 0-1 range.
(values - min) / (max - min)
- Args:
limits: tuple of (min, max) defining the normalization range
- classmethod pipe(func, *args, **kwargs)[source]#
Wrapper to give multidimensional transforms a more intuitive syntax. For a custom function ‘func’ with signature (*args, **kwargs), call as dim.pipe(func, *args, **kwargs).
- classmethod register(key, function)[source]#
Register a custom dim transform function which can from then on be referenced by the key.
- property str#
Casts values to strings or provides str accessor.
- holoviews.util.transform.easting_northing_to_lon_lat(easting, northing)[source]#
Projects the given easting, northing values into longitude, latitude coordinates.
easting and northing values are assumed to be in Web Mercator (aka Pseudo-Mercator or EPSG:3857) coordinates.
- Args:
easting northing
- Returns:
(longitude, latitude)
- class holoviews.util.transform.iloc(dim_expr)[source]#
Bases:
object
Implements integer array indexing for dim expressions.
- class holoviews.util.transform.loc(dim_expr)[source]#
Bases:
object
Implements loc for dim expressions.
- holoviews.util.transform.lognorm(values, min=None, max=None)[source]#
- Unity-based normalization on log scale.
Apply the same transformation as matplotlib.colors.LogNorm
- Args:
values: Array of values to be normalized min (float, optional): Lower bound of normalization range max (float, optional): Upper bound of normalization range
- Returns:
Array of normalized values
- holoviews.util.transform.lon_lat_to_easting_northing(longitude, latitude)[source]#
Projects the given longitude, latitude values into Web Mercator (aka Pseudo-Mercator or EPSG:3857) coordinates.
Longitude and latitude can be provided as scalars, Pandas columns, or Numpy arrays, and will be returned in the same form. Lists or tuples will be converted to Numpy arrays.
- Args:
longitude latitude
- Returns:
(easting, northing)
- Examples:
easting, northing = lon_lat_to_easting_northing(-74,40.71)
- easting, northing = lon_lat_to_easting_northing(
np.array([-74]),np.array([40.71])
)
df=pandas.DataFrame(dict(longitude=np.array([-74]),latitude=np.array([40.71]))) df.loc[:, ‘longitude’], df.loc[:, ‘latitude’] = lon_lat_to_easting_northing(
df.longitude,df.latitude
)
- holoviews.util.transform.norm(values, min=None, max=None)[source]#
Unity-based normalization to scale data into 0-1 range.
(values - min) / (max - min)
- Args:
values: Array of values to be normalized min (float, optional): Lower bound of normalization range max (float, optional): Upper bound of normalization range
- Returns:
Array of normalized values
- class holoviews.util.transform.xr_dim(obj, *args, **kwargs)[source]#
Bases:
dim
A subclass of dim which provides access to the xarray DataArray namespace along with tab-completion and type coercion allowing the expression to be applied on any gridded dataset.
- applies(dataset, strict=False)[source]#
Determines whether the dim transform can be applied to the Dataset, i.e. whether all referenced dimensions can be resolved.
- apply(dataset, flat=False, expanded=None, ranges=None, all_values=False, keep_index=False, compute=True, strict=False)[source]#
Evaluates the transform on the supplied dataset.
- Args:
dataset: Dataset object to evaluate the expression on flat: Whether to flatten the returned array expanded: Whether to use the expanded expand values ranges: Dictionary for ranges for normalization all_values: Whether to evaluate on all values
Whether to evaluate on all available values, for some element types, such as Graphs, this may include values not included in the referenced column
- keep_index: For data types that support indexes, whether the index
should be preserved in the result.
- compute: For data types that support lazy evaluation, whether
the result should be computed before it is returned.
- strict: Whether to strictly check for dimension matches
(if False, counts any dimensions with matching names as the same)
- Returns:
values: NumPy array computed by evaluating the expression
- bin(bins, labels=None)[source]#
Bins continuous values.
Bins continuous using the provided bins and assigns labels either computed from each bins center point or from the supplied labels.
- Args:
bins: List or array containing the bin boundaries labels: List of labels to assign to each bin
If the bins are length N the labels should be length N-1
- categorize(categories, default=None)[source]#
Replaces discrete values with supplied categories
Replaces discrete values in input array into a fixed set of categories defined either as a list or dictionary.
- Args:
categories: List or dict of categories to map inputs to default: Default value to assign if value not in categories
- clone(dimension=None, ops=None, dim_type=None)[source]#
Creates a clone of the dim expression optionally overriding the dim and ops.
- lognorm(limits=None)[source]#
- Unity-based normalization log scale.
Apply the same transformation as matplotlib.colors.LogNorm
- Args:
limits: tuple of (min, max) defining the normalization range
- norm(limits=None)[source]#
Unity-based normalization to scale data into 0-1 range.
(values - min) / (max - min)
- Args:
limits: tuple of (min, max) defining the normalization range
- classmethod pipe(func, *args, **kwargs)[source]#
Wrapper to give multidimensional transforms a more intuitive syntax. For a custom function ‘func’ with signature (*args, **kwargs), call as dim.pipe(func, *args, **kwargs).
- classmethod register(key, function)[source]#
Register a custom dim transform function which can from then on be referenced by the key.
- property str#
Casts values to strings or provides str accessor.
warnings
Module#
- exception holoviews.util.warnings.HoloviewsDeprecationWarning[source]#
Bases:
DeprecationWarning
A Holoviews-specific
DeprecationWarning
subclass. Used to selectively filter Holoviews deprecations for unconditional display.- add_note()#
Exception.add_note(note) – add a note to the exception
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception holoviews.util.warnings.HoloviewsUserWarning[source]#
Bases:
UserWarning
A Holoviews-specific
UserWarning
subclass. Used to selectively filter Holoviews warnings for unconditional display.- add_note()#
Exception.add_note(note) – add a note to the exception
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- holoviews.util.warnings.find_stack_level()[source]#
Find the first place in the stack that is not inside Holoviews and Param. Inspired by: pandas.util._exceptions.find_stack_level