INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns a dictionary of plot properties. | def _plot_properties(self, key, element):
"""
Returns a dictionary of plot properties.
"""
init = 'plot' not in self.handles
size_multiplier = self.renderer.size/100.
options = self._traverse_options(element, 'plot', ['width', 'height'], defaults=False)
logger = ... |
Activates the list of active tools | def _set_active_tools(self, plot):
"Activates the list of active tools"
for tool in self.active_tools:
if isinstance(tool, util.basestring):
tool_type = TOOL_TYPES[tool]
matching = [t for t in plot.toolbar.tools
if isinstance(t, too... |
Returns a dictionary of axis properties depending on the specified axis. | def _axis_properties(self, axis, key, plot, dimension=None,
ax_mapping={'x': 0, 'y': 1}):
"""
Returns a dictionary of axis properties depending
on the specified axis.
"""
# need to copy dictionary by calling dict() on it
axis_props = dict(theme_at... |
Updates plot parameters on every frame | def _update_plot(self, key, plot, element=None):
"""
Updates plot parameters on every frame
"""
plot.update(**self._plot_properties(key, element))
self._update_labels(key, plot, element)
self._update_title(key, plot, element)
self._update_grid(plot) |
Transforms non - string or integer types in datasource if the axis to be plotted on is categorical. Accepts the column data source data the columns corresponding to the axes and the dimensions for each axis changing the data inplace. | def _categorize_data(self, data, cols, dims):
"""
Transforms non-string or integer types in datasource if the
axis to be plotted on is categorical. Accepts the column data
source data, the columns corresponding to the axes and the
dimensions for each axis, changing the data inpla... |
Computes the aspect ratio of the plot | def get_aspect(self, xspan, yspan):
"""
Computes the aspect ratio of the plot
"""
if self.data_aspect:
return (yspan/xspan)*self.data_aspect
elif self.aspect == 'equal':
return xspan/yspan
elif self.aspect == 'square':
return 1
... |
Get factors for categorical axes. | def _get_factors(self, element):
"""
Get factors for categorical axes.
"""
xdim, ydim = element.dimensions()[:2]
xvals, yvals = [element.dimension_values(i, False)
for i in range(2)]
coords = tuple([v if vals.dtype.kind in 'SU' else dim.pprint_valu... |
Disables legends if show_legend is disabled. | def _process_legend(self):
"""
Disables legends if show_legend is disabled.
"""
for l in self.handles['plot'].legend:
l.items[:] = []
l.border_line_alpha = 0
l.background_fill_alpha = 0 |
Returns a Bokeh glyph object. | def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
properties = mpl_to_bokeh(properties)
plot_method = self._plot_methods.get('batched' if self.batched else 'single')
if isinstance(plot_method, tuple):
# Handle alternative ... |
Attaches renderer to hover tool and processes tooltips to ensure datetime data is displayed correctly. | def _postprocess_hover(self, renderer, source):
"""
Attaches renderer to hover tool and processes tooltips to
ensure datetime data is displayed correctly.
"""
hover = self.handles.get('hover')
if hover is None:
return
if hover.renderers == 'auto':
... |
Initializes a new plot object with the last available frame. | def initialize_plot(self, ranges=None, plot=None, plots=None, source=None):
"""
Initializes a new plot object with the last available frame.
"""
# Get element key and ranges for frame
if self.batched:
element = [el for el in self.hmap.data.values() if el][-1]
... |
Updates an existing plot with data corresponding to the key. | def update_frame(self, key, ranges=None, plot=None, element=None):
"""
Updates an existing plot with data corresponding
to the key.
"""
reused = isinstance(self.hmap, DynamicMap) and (self.overlaid or self.batched)
if not reused and element is None:
element = ... |
Determines if the bokeh model was just changed on the frontend. Useful to suppress boomeranging events e. g. when the frontend just sent an update to the x_range this should not trigger an update on the backend. | def model_changed(self, model):
"""
Determines if the bokeh model was just changed on the frontend.
Useful to suppress boomeranging events, e.g. when the frontend
just sent an update to the x_range this should not trigger an
update on the backend.
"""
callbacks = ... |
Property to determine whether the current frame should have framewise normalization enabled. Required for bokeh plotting classes to determine whether to send updated ranges for each frame. | def framewise(self):
"""
Property to determine whether the current frame should have
framewise normalization enabled. Required for bokeh plotting
classes to determine whether to send updated ranges for each
frame.
"""
current_frames = [el for f in self.traverse(la... |
Returns a Bokeh glyph object. | def _init_glyph(self, plot, mapping, properties, key):
"""
Returns a Bokeh glyph object.
"""
properties = mpl_to_bokeh(properties)
plot_method = '_'.join(key.split('_')[:-1])
renderer = getattr(plot, plot_method)(**dict(properties, **mapping))
return renderer, ren... |
Returns a Bokeh glyph object and optionally creates a colorbar. | def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object and optionally creates a colorbar.
"""
ret = super(ColorbarPlot, self)._init_glyph(plot, mapping, properties)
if self.colorbar:
for k, v in list(self.handles.items()):
i... |
Processes the list of tools to be supplied to the plot. | def _init_tools(self, element, callbacks=[]):
"""
Processes the list of tools to be supplied to the plot.
"""
hover_tools = {}
init_tools, tool_types = [], []
for key, subplot in self.subplots.items():
el = element.get(key)
if el is not None:
... |
Merges tools on the overlay with those on the subplots. | def _merge_tools(self, subplot):
"""
Merges tools on the overlay with those on the subplots.
"""
if self.batched and 'hover' in subplot.handles:
self.handles['hover'] = subplot.handles['hover']
elif 'hover' in subplot.handles and 'hover_tools' in self.handles:
... |
Update the internal state of the Plot to represent the given key tuple ( where integers represent frames ). Returns this state. | def update_frame(self, key, ranges=None, element=None):
"""
Update the internal state of the Plot to represent the given
key tuple (where integers represent frames). Returns this
state.
"""
reused = isinstance(self.hmap, DynamicMap) and self.overlaid
if not reused... |
Returns list of supported formats for a particular backend. | def list_formats(format_type, backend=None):
"""
Returns list of supported formats for a particular
backend.
"""
if backend is None:
backend = Store.current_backend
mode = Store.renderers[backend].mode if backend in Store.renderers else None
else:
split = backend.split(':... |
Given a keyword specification validate and compute options | def get_options(cls, items, options, warnfn):
"Given a keyword specification, validate and compute options"
options = cls.update_options(options, items)
for keyword in cls.defaults:
if keyword in items:
value = items[keyword]
allowed = cls.allowed[keyw... |
Given the keyword string parse a dictionary of options. | def extract_keywords(cls, line, items):
"""
Given the keyword string, parse a dictionary of options.
"""
unprocessed = list(reversed(line.split('=')))
while unprocessed:
chunk = unprocessed.pop()
key = None
if chunk.strip() in cls.allowed:
... |
Validation of edge cases and incompatible options | def _validate(cls, options, items, warnfn):
"Validation of edge cases and incompatible options"
if 'html' in Store.display_formats:
pass
elif 'fig' in items and items['fig'] not in Store.display_formats:
msg = ("Requesting output figure format %r " % items['fig']
... |
Switch default options and backend if new backend is supplied in items. | def update_options(cls, options, items):
"""
Switch default options and backend if new backend is supplied in
items.
"""
# Get new backend
backend_spec = items.get('backend', Store.current_backend)
split = backend_spec.split(':')
backend, mode = split if l... |
Set options on current Renderer. | def _set_render_options(cls, options, backend=None):
"""
Set options on current Renderer.
"""
if backend:
backend = backend.split(':')[0]
else:
backend = Store.current_backend
cls.set_backend(backend)
if 'widgets' in options:
o... |
Extended version of the built - in help that supports parameterized functions and objects. A pattern ( regular expression ) may be used to filter the output and if recursive is set to True documentation for the supplied object is shown. Note that the recursive option will only work with an object instance and not a cla... | def help(obj, visualization=True, ansi=True, backend=None,
recursive=False, pattern=None):
"""
Extended version of the built-in help that supports parameterized
functions and objects. A pattern (regular expression) may be used to
filter the output and if recursive is set to True, documentation ... |
Returns a Bokeh glyph object. | def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
box = Span(level=properties.get('level', 'glyph'), **mapping)
plot.renderers.append(box)
return None, box |
Returns a Bokeh glyph object. | def _init_glyph(self, plot, mapping, properties, key):
"""
Returns a Bokeh glyph object.
"""
properties.pop('legend', None)
if key == 'arrow':
properties.pop('source')
arrow_end = mapping.pop('arrow_end')
arrow_start = mapping.pop('arrow_start'... |
Initializes a new plot object with the last available frame. | def initialize_plot(self, ranges=None, plot=None, plots=None, source=None):
"""
Initializes a new plot object with the last available frame.
"""
# Get element key and ranges for frame
element = self.hmap.last
key = self.keys[-1]
self.current_frame = element
... |
Updates an existing plot with data corresponding to the key. | def update_frame(self, key, ranges=None, plot=None):
"""
Updates an existing plot with data corresponding
to the key.
"""
element = self._get_frame(key)
text, _, _ = self.get_data(element, ranges, {})
self.handles['plot'].text = text |
Splits a dataframe of paths separated by NaNs into individual dataframes. | def split_dataframe(path_df):
"""
Splits a dataframe of paths separated by NaNs into individual
dataframes.
"""
splits = np.where(path_df.iloc[:, 0].isnull())[0]+1
return [df for df in np.split(path_df, splits) if len(df) > 1] |
Reduces any Overlay or NdOverlay of Elements into a single xarray Dataset that can be aggregated. | def get_agg_data(cls, obj, category=None):
"""
Reduces any Overlay or NdOverlay of Elements into a single
xarray Dataset that can be aggregated.
"""
paths = []
if isinstance(obj, Graph):
obj = obj.edgepaths
kdims = list(obj.kdims)
vdims = list(... |
Optimized aggregation for NdOverlay objects by aggregating each Element in an NdOverlay individually avoiding having to concatenate items in the NdOverlay. Works by summing sum and count aggregates and applying appropriate masking for NaN values. Mean aggregation is also supported by dividing sum and count aggregates. ... | def _aggregate_ndoverlay(self, element, agg_fn):
"""
Optimized aggregation for NdOverlay objects by aggregating each
Element in an NdOverlay individually avoiding having to concatenate
items in the NdOverlay. Works by summing sum and count aggregates and
applying appropriate mask... |
Concatenates an NdOverlay of Image types into a single 3D xarray Dataset. | def concatenate(cls, overlay):
"""
Concatenates an NdOverlay of Image types into a single 3D
xarray Dataset.
"""
if not isinstance(overlay, NdOverlay):
raise ValueError('Only NdOverlays can be concatenated')
xarr = xr.concat([v.data.transpose() for v in overla... |
Cast uint32 RGB image to 4 uint8 channels. | def uint32_to_uint8(cls, img):
"""
Cast uint32 RGB image to 4 uint8 channels.
"""
return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,))) |
Autover is purely a build time dependency in all cases ( conda and pip ) except for when you use pip s remote git support [ git + url ] as 1 ) you need a dynamically changing version and 2 ) the environment starts off clean with zero dependencies installed. This function acts as a fallback to make Version available unt... | def embed_version(basepath, ref='v0.2.2'):
"""
Autover is purely a build time dependency in all cases (conda and
pip) except for when you use pip's remote git support [git+url] as
1) you need a dynamically changing version and 2) the environment
starts off clean with zero dependencies installed.
... |
Helper to get the current version from either git describe or the. version file ( if available ). | def get_setup_version(reponame):
"""
Helper to get the current version from either git describe or the
.version file (if available).
"""
import json
basepath = os.path.split(__file__)[0]
version_file_path = os.path.join(basepath, reponame, '.version')
try:
from param import versi... |
Verifies that a fake subpackage path for assets ( notebooks svgs pngs etc ) both exists and is populated with files. | def check_pseudo_package(path):
"""
Verifies that a fake subpackage path for assets (notebooks, svgs,
pngs etc) both exists and is populated with files.
"""
if not os.path.isdir(path):
raise Exception("Please make sure pseudo-package %s exists." % path)
else:
assets = os.listdir(... |
Walks a directory and records all packages and file extensions. | def walker(top, names):
"""
Walks a directory and records all packages and file extensions.
"""
global packages, extensions
if any(exc in top for exc in excludes):
return
package = top[top.rfind('holoviews'):].replace(os.path.sep, '.')
packages.append(package)
for name in names:
... |
Copies the notebooks to the supplied path. | def examples(path='holoviews-examples', verbose=False, force=False, root=__file__):
"""
Copies the notebooks to the supplied path.
"""
filepath = os.path.abspath(os.path.dirname(root))
example_dir = os.path.join(filepath, './examples')
if not os.path.exists(example_dir):
example_dir = os... |
Generates pseudo - packages for the examples directory. | def package_assets(example_path):
"""
Generates pseudo-packages for the examples directory.
"""
examples(example_path, force=True, root=__file__)
for root, dirs, files in os.walk(example_path):
walker(root, dirs+files)
setup_args['packages'] += packages
for p, exts in extensions.item... |
Allows selecting data by the slices sets and scalar values along a particular dimension. The indices should be supplied as keywords mapping between the selected dimension and value. Additionally selection_specs ( taking the form of a list of type. group. label strings types or functions ) may be supplied which will ens... | def select(self, selection_specs=None, selection_mode='edges', **selection):
"""
Allows selecting data by the slices, sets and scalar values
along a particular dimension. The indices should be supplied as
keywords mapping between the selected dimension and
value. Additionally sel... |
Computes the node positions the first time they are requested if no explicit node information was supplied. | def nodes(self):
"""
Computes the node positions the first time they are requested
if no explicit node information was supplied.
"""
if self._nodes is None:
self._nodes = layout_nodes(self, only_nodes=True)
return self._nodes |
Returns the fixed EdgePaths or computes direct connections between supplied nodes. | def edgepaths(self):
"""
Returns the fixed EdgePaths or computes direct connections
between supplied nodes.
"""
if self._edgepaths:
return self._edgepaths
if pd is None:
paths = connect_edges(self)
else:
paths = connect_edges_pd... |
Generate a HoloViews Graph from a networkx. Graph object and networkx layout function or dictionary of node positions. Any keyword arguments will be passed to the layout function. By default it will extract all node and edge attributes from the networkx. Graph but explicit node information may also be supplied. Any non... | def from_networkx(cls, G, positions, nodes=None, **kwargs):
"""
Generate a HoloViews Graph from a networkx.Graph object and
networkx layout function or dictionary of node positions.
Any keyword arguments will be passed to the layout
function. By default it will extract all node a... |
Uses Delauney triangulation to compute triangle simplices for each point. | def from_vertices(cls, data):
"""
Uses Delauney triangulation to compute triangle simplices for
each point.
"""
try:
from scipy.spatial import Delaunay
except:
raise ImportError("Generating triangles from points requires, "
... |
Returns the EdgePaths by generating a triangle for each simplex. | def edgepaths(self):
"""
Returns the EdgePaths by generating a triangle for each simplex.
"""
if self._edgepaths:
return self._edgepaths
elif not len(self):
edgepaths = self.edge_type([], kdims=self.nodes.kdims[:2])
self._edgepaths = edgepaths
... |
Allows selecting data by the slices sets and scalar values along a particular dimension. The indices should be supplied as keywords mapping between the selected dimension and value. Additionally selection_specs ( taking the form of a list of type. group. label strings types or functions ) may be supplied which will ens... | def select(self, selection_specs=None, **selection):
"""
Allows selecting data by the slices, sets and scalar values
along a particular dimension. The indices should be supplied as
keywords mapping between the selected dimension and
value. Additionally selection_specs (taking the... |
Extends the ElementPlot _finalize_axis method to set appropriate labels and axes options for 3D Plots. | def _finalize_axis(self, key, **kwargs):
"""
Extends the ElementPlot _finalize_axis method to set appropriate
labels, and axes options for 3D Plots.
"""
axis = self.handles['axis']
self.handles['fig'].set_frameon(False)
axis.grid(self.show_grid)
axis.view_... |
Given a Dataset object and a dictionary with dimension keys and selection keys ( i. e tuple ranges slices sets lists or literals ) return a boolean mask over the rows in the Dataset object that have been selected. | def select_mask(cls, dataset, selection):
"""
Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e tuple ranges, slices, sets, lists or literals)
return a boolean mask over the rows in the Dataset object that
have been selected.
"""
... |
Given a dataset object and data in the appropriate format for the interface return a simple scalar. | def unpack_scalar(cls, dataset, data):
"""
Given a dataset object and data in the appropriate format for
the interface, return a simple scalar.
"""
import dask.dataframe as dd
if len(data.columns) > 1 or len(data) != 1:
return data
if isinstance(data, ... |
Dask does not support iloc therefore iloc will execute the call graph and lose the laziness of the operation. | def iloc(cls, dataset, index):
"""
Dask does not support iloc, therefore iloc will execute
the call graph and lose the laziness of the operation.
"""
rows, cols = index
scalar = False
if isinstance(cols, slice):
cols = [d.name for d in dataset.dimensio... |
Populate the sourceLinks and targetLinks for each node. Also if the source and target are not objects assume they are indices. | def computeNodeLinks(cls, element, graph):
"""
Populate the sourceLinks and targetLinks for each node.
Also, if the source and target are not objects, assume they are indices.
"""
index = element.nodes.kdims[-1]
node_map = {}
if element.nodes.vdims:
va... |
Compute the value ( size ) of each node by summing the associated links. | def computeNodeValues(cls, graph):
"""
Compute the value (size) of each node by summing the associated links.
"""
for node in graph['nodes']:
source_val = np.sum([l['value'] for l in node['sourceLinks']])
target_val = np.sum([l['value'] for l in node['targetLinks'... |
Iteratively assign the depth ( x - position ) for each node. Nodes are assigned the maximum depth of incoming neighbors plus one ; nodes with no incoming links are assigned depth zero while nodes with no outgoing links are assigned the maximum depth. | def computeNodeDepths(self, graph):
"""
Iteratively assign the depth (x-position) for each node.
Nodes are assigned the maximum depth of incoming neighbors plus one;
nodes with no incoming links are assigned depth zero, while
nodes with no outgoing links are assigned the maximum ... |
Get data from histogram including bin_ranges and values. | def _process_hist(self, hist):
"""
Get data from histogram, including bin_ranges and values.
"""
self.cyclic = hist.get_dimension(0).cyclic
x = hist.kdims[0]
edges = hist.interface.coords(hist, x, edges=True)
values = hist.dimension_values(1)
hist_vals = n... |
Compute the ticks either as cyclic values in degrees or as roughly evenly spaced bin centers. | def _compute_ticks(self, element, edges, widths, lims):
"""
Compute the ticks either as cyclic values in degrees or as roughly
evenly spaced bin centers.
"""
if self.xticks is None or not isinstance(self.xticks, int):
return None
if self.cyclic:
x0... |
Get axis settings options including ticks x - and y - labels and limits. | def _process_axsettings(self, hist, lims, ticks):
"""
Get axis settings options including ticks, x- and y-labels
and limits.
"""
axis_settings = dict(zip(self.axis_settings, [None, None, (None if self.overlaid else ticks)]))
return axis_settings |
Update all the artists in the histogram. Subclassable to allow updating of further artists. | def _update_artists(self, key, hist, edges, hvals, widths, lims, ranges):
"""
Update all the artists in the histogram. Subclassable to
allow updating of further artists.
"""
plot_vals = zip(self.handles['artist'], edges, hvals, widths)
for bar, edge, height, width in plot... |
Subclassed to offset histogram by defined amount. | def _process_hist(self, hist):
"""
Subclassed to offset histogram by defined amount.
"""
edges, hvals, widths, lims, isdatetime = super(SideHistogramPlot, self)._process_hist(hist)
offset = self.offset * lims[3]
hvals *= 1-self.offset
hvals += offset
lims ... |
Process the bars and draw the offset line as necessary. If a color map is set in the style of the main ViewableElement object color the bars appropriately respecting the required normalization settings. | def _update_plot(self, key, element, bars, lims, ranges):
"""
Process the bars and draw the offset line as necessary. If a
color map is set in the style of the 'main' ViewableElement object, color
the bars appropriately, respecting the required normalization
settings.
"""... |
Use the given cmap to color the bars applying the correct color ranges as necessary. | def _colorize_bars(self, cmap, bars, element, main_range, dim):
"""
Use the given cmap to color the bars, applying the correct
color ranges as necessary.
"""
cmap_range = main_range[1] - main_range[0]
lower_bound = main_range[0]
colors = np.array(element.dimension... |
Compute colorbar offset and update separator line if map is non - zero. | def _update_separator(self, offset):
"""
Compute colorbar offset and update separator line
if map is non-zero.
"""
offset_line = self.handles['offset_line']
if offset == 0:
offset_line.set_visible(False)
else:
offset_line.set_visible(True)
... |
Get unique index value for each bar | def _get_values(self):
"""
Get unique index value for each bar
"""
(gi, _), (ci, _), (si, _) = self._get_dims(self.hmap.last)
ndims = self.hmap.last.ndims
dims = self.hmap.last.kdims
dimensions = []
values = {}
for vidx, vtype in zip([gi, ci, si], ... |
Computes color and hatch combinations by any combination of the group category and stack. | def _compute_styles(self, element, style_groups):
"""
Computes color and hatch combinations by
any combination of the 'group', 'category'
and 'stack'.
"""
style = self.lookup_options(element, 'style')[0]
sopts = []
for sopt in ['color', 'hatch']:
... |
Apply ticks with appropriate offsets. | def _finalize_ticks(self, axis, element, xticks, yticks, zticks):
"""
Apply ticks with appropriate offsets.
"""
yalignments = None
if xticks is not None:
ticks, labels, yalignments = zip(*sorted(xticks, key=lambda x: x[0]))
xticks = (list(ticks), list(labe... |
Group inherited from main element | def group(self):
"Group inherited from main element"
if self.main and self.main.group != type(self.main).__name__:
return self.main.group
else:
return 'AdjointLayout' |
Clone object and apply new group and/ or label. | def relabel(self, label=None, group=None, depth=1):
"""Clone object and apply new group and/or label.
Applies relabeling to child up to the supplied depth.
Args:
label (str, optional): New label to apply to returned object
group (str, optional): New group to apply to re... |
Return the values along the requested dimension. | def dimension_values(self, dimension, expanded=True, flat=True):
"""Return the values along the requested dimension.
Applies to the main object in the AdjointLayout.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
... |
Compute a dict of { ( row column ): ( key value ) } elements from the current set of items and specified number of columns. | def grid_items(self):
"""
Compute a dict of {(row,column): (key, value)} elements from the
current set of items and specified number of columns.
"""
if list(self.keys()) == []: return {}
cols = self._max_cols
return {(idx // cols, idx % cols): (key, item)
... |
Returns another NdLayout constituted of the last views of the individual elements ( if they are maps ). | def last(self):
"""
Returns another NdLayout constituted of the last views of the
individual elements (if they are maps).
"""
last_items = []
for (k, v) in self.items():
if isinstance(v, NdMapping):
item = (k, v.clone((v.last_key, v.last)))
... |
Clones the NdLayout overriding data and parameters. | def clone(self, *args, **overrides):
"""Clones the NdLayout, overriding data and parameters.
Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
new_type (optional): Type to cast object to
*args: Add... |
Tuple indicating the number of rows and columns in the Layout. | def shape(self):
"Tuple indicating the number of rows and columns in the Layout."
num = len(self)
if num <= self._max_cols:
return (1, num)
nrows = num // self._max_cols
last_row_cols = num % self._max_cols
return nrows+(1 if last_row_cols else 0), min(num, se... |
Clones the Layout overriding data and parameters. | def clone(self, *args, **overrides):
"""Clones the Layout, overriding data and parameters.
Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
new_type (optional): Type to cast object to
*args: Addit... |
Returns a json diff required to update an existing plot with the latest plot data. | def diff(self, plot, serialize=True):
"""
Returns a json diff required to update an existing plot with
the latest plot data.
"""
diff = plot.state
if serialize:
return json.dumps(diff, cls=utils.PlotlyJSONEncoder)
else:
return diff |
Loads the plotly notebook resources. | def load_nb(cls, inline=True):
"""
Loads the plotly notebook resources.
"""
from IPython.display import publish_display_data
cls._loaded = True
init_notebook_mode(connected=not inline)
publish_display_data(data={MIME_TYPES['jlab-hv-load']:
... |
Given a dataset object and data in the appropriate format for the interface return a simple scalar. | def unpack_scalar(cls, dataset, data):
"""
Given a dataset object and data in the appropriate format for
the interface, return a simple scalar.
"""
if len(data) != 1:
return data
key = list(data.keys())[0]
if len(data[key]) == 1 and key in dataset.vdi... |
Utility used to make sure AST parser does not choke on unrecognized magics. | def comment_out_magics(source):
"""
Utility used to make sure AST parser does not choke on unrecognized
magics.
"""
filtered = []
for line in source.splitlines():
if line.strip().startswith('%'):
filtered.append('# ' + line)
else:
filtered.append(line)
... |
If a cell ends in an expression that could be displaying a HoloViews object ( as determined using the AST ) wrap it with a given prefix and suffix string. | def wrap_cell_expression(source, template='{expr}'):
"""
If a cell ends in an expression that could be displaying a HoloViews
object (as determined using the AST), wrap it with a given prefix
and suffix string.
If the cell doesn't end in an expression, return the source unchanged.
"""
cell_... |
Given the source of a cell filter out the given magic and collect the lines using the magic into a list. | def filter_magic(source, magic, strip=True):
"""
Given the source of a cell, filter out the given magic and collect
the lines using the magic into a list.
If strip is True, the IPython syntax part of the magic (e.g %magic
or %%magic) is stripped from the returned lines.
"""
filtered, magic_... |
Given the source of a cell filter out all cell and line magics. | def strip_magics(source):
"""
Given the source of a cell, filter out all cell and line magics.
"""
filtered=[]
for line in source.splitlines():
if not line.startswith('%') or line.startswith('%%'):
filtered.append(line)
return '\n'.join(filtered) |
Given a cell s source replace line magics using a formatting template where { line } is the string that follows the magic. | def replace_line_magic(source, magic, template='{line}'):
"""
Given a cell's source, replace line magics using a formatting
template, where {line} is the string that follows the magic.
"""
filtered = []
for line in source.splitlines():
if line.strip().startswith(magic):
subst... |
Given some source html substitute and annotated as applicable | def replace(self, src):
"Given some source html substitute and annotated as applicable"
for html in self.substitutions.keys():
if src == html:
annotation = self.annotation % self.substitutions[src][1]
return annotation + self.substitutions[src][0]
retu... |
Extract the subplot number from a subplot value string. | def _get_subplot_number(subplot_val):
"""
Extract the subplot number from a subplot value string.
'x3' -> 3
'polar2' -> 2
'scene' -> 1
'y' -> 1
Note: the absence of a subplot number (e.g. 'y') is treated by plotly as
a subplot number of 1
Parameters
----------
subplot_val:... |
Make sure a layout subplot property is initialized for every subplot that is referenced by a trace in the figure. | def _normalize_subplot_ids(fig):
"""
Make sure a layout subplot property is initialized for every subplot that
is referenced by a trace in the figure.
For example, if a figure contains a `scatterpolar` trace with the `subplot`
property set to `polar3`, this function will make sure the figure's layo... |
Given an input figure return a dict containing the max subplot number for each subplot type in the figure | def _get_max_subplot_ids(fig):
"""
Given an input figure, return a dict containing the max subplot number
for each subplot type in the figure
Parameters
----------
fig: dict
A plotly figure dict
Returns
-------
dict
A dict from subplot type strings to integers indic... |
Apply offsets to the subplot id numbers in a figure. | def _offset_subplot_ids(fig, offsets):
"""
Apply offsets to the subplot id numbers in a figure.
Note: This function mutates the input figure dict
Note: This function assumes that the normalize_subplot_ids function has
already been run on the figure, so that all layout subplot properties in
use... |
Scale a figure and translate it to sub - region of the original figure canvas. | def _scale_translate(fig, scale_x, scale_y, translate_x, translate_y):
"""
Scale a figure and translate it to sub-region of the original
figure canvas.
Note: If the input figure has a title, this title is converted into an
annotation and scaled along with the rest of the figure.
Note: This fun... |
Merge a sub - figure into a parent figure | def merge_figure(fig, subfig):
"""
Merge a sub-figure into a parent figure
Note: This function mutates the input fig dict, but it does not mutate
the subfig dict
Parameters
----------
fig: dict
The plotly figure dict into which the sub figure will be merged
subfig: dict
... |
Merge layout objects recursively | def _merge_layout_objs(obj, subobj):
"""
Merge layout objects recursively
Note: This function mutates the input obj dict, but it does not mutate
the subobj dict
Parameters
----------
obj: dict
dict into which the sub-figure dict will be merged
subobj: dict
dict that sil... |
Compute normalized domain tuples for a list of widths and a subplot spacing value | def _compute_subplot_domains(widths, spacing):
"""
Compute normalized domain tuples for a list of widths and a subplot
spacing value
Parameters
----------
widths: list of float
List of the desired withs of each subplot. The length of this list
is also the specification of the nu... |
Construct a figure from a 2D grid of sub - figures | def figure_grid(figures_grid,
row_heights=None,
column_widths=None,
row_spacing=0.15,
column_spacing=0.15,
share_xaxis=False,
share_yaxis=False):
"""
Construct a figure from a 2D grid of sub-figures
Parameters
... |
Converts a cmap spec to a plotly colorscale | def get_colorscale(cmap, levels=None, cmin=None, cmax=None):
"""Converts a cmap spec to a plotly colorscale
Args:
cmap: A recognized colormap by name or list of colors
levels: A list or integer declaring the color-levels
cmin: The lower bound of the color range
cmax: The upper b... |
Given a HoloViews Viewable return a corresponding plot instance. | def get_plot(self_or_cls, obj, renderer=None, **kwargs):
"""
Given a HoloViews Viewable return a corresponding plot instance.
"""
if isinstance(obj, DynamicMap) and obj.unbounded:
dims = ', '.join('%r' % dim for dim in obj.unbounded)
msg = ('DynamicMap cannot be d... |
Helper method to be used in the __call__ method to get a suitable plot or widget object and the appropriate format. | def _validate(self, obj, fmt, **kwargs):
"""
Helper method to be used in the __call__ method to get a
suitable plot or widget object and the appropriate format.
"""
if isinstance(obj, tuple(self.widgets.values())):
return obj, 'html'
plot = self.get_plot(obj, ... |
Apply the post - render hooks to the data. | def _apply_post_render_hooks(self, data, obj, fmt):
"""
Apply the post-render hooks to the data.
"""
hooks = self.post_render_hooks.get(fmt,[])
for hook in hooks:
try:
data = hook(data, obj)
except Exception as e:
self.param... |
Renders plot or data structure and wraps the output in HTML. The comm argument defines whether the HTML output includes code to initialize a Comm if the plot supplies one. | def html(self, obj, fmt=None, css=None, **kwargs):
"""
Renders plot or data structure and wraps the output in HTML.
The comm argument defines whether the HTML output includes
code to initialize a Comm, if the plot supplies one.
"""
plot, fmt = self._validate(obj, fmt)
... |
Returns data and metadata dictionaries containing HTML and JS components to include render in app notebook or standalone document. Depending on the backend the fmt defines the format embedded in the HTML e. g. png or svg. If comm is enabled the JS code will set up a Websocket comm channel using the currently defined Co... | def components(self, obj, fmt=None, comm=True, **kwargs):
"""
Returns data and metadata dictionaries containing HTML and JS
components to include render in app, notebook, or standalone
document. Depending on the backend the fmt defines the format
embedded in the HTML, e.g. png or... |
Generates a static HTML with the rendered object in the supplied format. Allows supplying a template formatting string with fields to interpolate js css and the main html. | def static_html(self, obj, fmt=None, template=None):
"""
Generates a static HTML with the rendered object in the
supplied format. Allows supplying a template formatting string
with fields to interpolate 'js', 'css' and the main 'html'.
"""
js_html, css_html = self.html_as... |
Render and export object as a widget to a static HTML file. Allows supplying a custom template formatting string with fields to interpolate js css and the main html containing the widget. Also provides options to export widget data to a json file in the supplied json_path ( defaults to current path ). | def export_widgets(self_or_cls, obj, filename, fmt=None, template=None,
json=False, json_path='', **kwargs):
"""
Render and export object as a widget to a static HTML
file. Allows supplying a custom template formatting string
with fields to interpolate 'js', 'css' ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.