In [1]:
import numpy as np
import scipy
import holoviews as hv
hv.extension('matplotlib')
%output fig='svg'


/usr/local/lib/python3.5/dist-packages/seaborn/apionly.py:6: UserWarning: As seaborn no longer sets a default style on import, the seaborn.apionly module is deprecated. It will be removed in a future version.
  warnings.warn(msg, UserWarning)

In [2]:
np.random.seed(1)
data = np.random.randn(25000)
frequencies, edges = np.histogram(data, 110)
print('Values: %s, Edges: %s' % (frequencies.shape[0], edges.shape[0]))
hv.Histogram(frequencies, edges)


Values: 110, Edges: 111
Out[2]:

In [6]:
hv.help(hv.Histogram)


Histogram

Online example: http://holoviews.org/reference/elements/matplotlib/Histogram.html

-------------
Style Options
-------------

	align, alpha, c, capsize, color, ec, ecolor, edgecolor, error_kw, facecolor, fc, hatch, linewidth, log, lw, visible

(Consult matplotlib's documentation for more information.)

------------
Plot Options
------------

The plot options are the parameters of the plotting class:

Parameters of 'HistogramPlot'
=============================

Parameters changed from their default values are marked in red.
Soft bound values are marked in cyan.
C/V= Constant/Variable, RO/RW = ReadOnly/ReadWrite, AN=Allow None

Name                             Value                    Type         Bounds     Mode  

apply_extents                     True                  Boolean        (0, 1)     V RW  
apply_ranges                      True                  Boolean        (0, 1)     V RW  
apply_ticks                       True                  Boolean        (0, 1)     V RW  
aspect                          'square'               Parameter                  V RW  
bgcolor                           None               ClassSelector              V RW AN 
fig_alpha                         1.0                    Number        (0, 1)     V RW  
fig_bounds              (0.15, 0.15, 0.85, 0.85)      NumericTuple                V RW  
fig_inches                         4                   Parameter                  V RW  
fig_latex                        False                  Boolean        (0, 1)     V RW  
fig_rcparams                       {}                     Dict                    V RW  
fig_size                         100.0                   Number      (1, None)    V RW  
final_hooks                        []                   HookList     (0, None)    V RW  
finalize_hooks                     []                   HookList     (0, None)    V RW  
fontsize                          None                 Parameter                V RW AN 
initial_hooks                      []                   HookList     (0, None)    V RW  
invert_axes                      False               ObjectSelector               V RW  
invert_xaxis                     False                  Boolean        (0, 1)     V RW  
invert_yaxis                     False                  Boolean        (0, 1)     V RW  
invert_zaxis                     False                  Boolean        (0, 1)     V RW  
labelled                       ['x', 'y']                 List       (0, None)    V RW  
logx                             False                  Boolean        (0, 1)     V RW  
logy                             False                  Boolean        (0, 1)     V RW  
logz                             False                  Boolean        (0, 1)     V RW  
normalize                         True                  Boolean        (0, 1)     V RW  
projection                        None                 Parameter                V RW AN 
show_frame                       False                  Boolean        (0, 1)     V RW  
show_grid                        False                  Boolean        (0, 1)     V RW  
show_legend                       True                  Boolean        (0, 1)     V RW  
show_title                        True                  Boolean        (0, 1)     V RW  
sublabel_format                   None                   String                 V RW AN 
sublabel_position            (-0.35, 0.85)            NumericTuple                V RW  
sublabel_size                      18                    Number                   V RW  
title_format        '{label} {group}\n{dimensions}'      String                   V RW  
xaxis                           'bottom'             ObjectSelector               V RW  
xrotation                          0                    Integer       (0, 360)    V RW  
xticks                            None                 Parameter                V RW AN 
yaxis                            'left'              ObjectSelector               V RW  
yrotation                          0                    Integer       (0, 360)    V RW  
yticks                            None                 Parameter                V RW AN 
zaxis                             True                  Boolean        (0, 1)     V RW  
zrotation                          0                    Integer       (0, 360)    V RW  
zticks                            None                 Parameter                V RW AN 

Parameter docstrings:
=====================

apply_extents:     Whether to apply extent overrides on the Elements
apply_ranges:      Whether to compute the plot bounds from the data itself.
apply_ticks:       Whether to apply custom ticks.
aspect:            The aspect ratio mode of the plot. By default, a plot may
                   select its own appropriate aspect ratio but sometimes it may
                   be necessary to force a square aspect ratio (e.g. to display
                   the plot as an element of a grid). The modes 'auto' and
                   'equal' correspond to the axis modes of the same name in
                   matplotlib, a numeric value may also be passed.
bgcolor:           If set bgcolor overrides the background color of the axis.
fig_alpha:         Alpha of the overall figure background.
fig_bounds:        The bounds of the overall figure as a 4-tuple of the form
                   (left, bottom, right, top), defining the size of the border
                   around the subplots.
fig_inches:        The overall matplotlib figure size in inches.  May be set as
                   an integer in which case it will be used to autocompute a
                   size. Alternatively may be set with an explicit tuple or list,
                   in which case it will be applied directly after being scaled
                   by fig_size. If either the width or height is set to None,
                   it will be computed automatically.
fig_latex:         Whether to use LaTeX text in the overall figure.
fig_rcparams:      matplotlib rc parameters to apply to the overall figure.
fig_size:          Size relative to the supplied overall fig_inches in percent.
final_hooks:       Optional list of hooks called when finalizing an axis.
                   The hook is passed the plot object and the displayed
                   object, other plotting handles can be accessed via plot.handles.
finalize_hooks:    Optional list of hooks called when finalizing an axis.
                   The hook is passed the plot object and the displayed
                   object, other plotting handles can be accessed via plot.handles.
fontsize:          Specifies various fontsizes of the displayed text.
                   
                   Finer control is available by supplying a dictionary where any
                   unmentioned keys reverts to the default sizes, e.g:
                   
                      {'ticks':20, 'title':15,
                       'ylabel':5, 'xlabel':5,
                       'legend':8, 'legend_title':13}
                   
                   You can set the fontsize of both 'ylabel' and 'xlabel' together
                   using the 'labels' key.
initial_hooks:     Optional list of hooks called before plotting the data onto
                   the axis. The hook is passed the plot object and the displayed
                   object, other plotting handles can be accessed via plot.handles.
invert_axes:       Inverts the axes of the plot. Note that this parameter may not
                   always be respected by all plots but should be respected by
                   adjoined plots when appropriate.
invert_xaxis:      Whether to invert the plot x-axis.
invert_yaxis:      Whether to invert the plot y-axis.
invert_zaxis:      Whether to invert the plot z-axis.
labelled:          Whether to plot the 'x' and 'y' labels.
logx:              Whether to apply log scaling to the x-axis of the Chart.
logy:              Whether to apply log scaling to the y-axis of the Chart.
logz:              Whether to apply log scaling to the y-axis of the Chart.
normalize:         Whether to compute ranges across all Elements at this level
                   of plotting. Allows selecting normalization at different levels
                   for nested data containers.
projection:        The projection of the plot axis, default of None is equivalent to
                   2D plot, '3d' and 'polar' are also supported by matplotlib by default.
                   May also supply a custom projection that is either a matplotlib
                   projection type or implements the `_as_mpl_axes` method.
show_frame:        Whether or not to show a complete frame around the plot.
show_grid:         Whether to show a Cartesian grid on the plot.
show_legend:       Whether to show legend for the plot.
show_title:        Whether to display the plot title.
sublabel_format:   Allows labeling the subaxes in each plot with various formatters
                   including {Alpha}, {alpha}, {numeric} and {roman}.
sublabel_position: Position relative to the plot for placing the optional subfigure label.
sublabel_size:     Size of optional subfigure label.
title_format:      The formatting string for the title of this plot, allows defining
                   a label group separator and dimension labels.
xaxis:             Whether and where to display the xaxis, bare options allow suppressing
                   all axis labels including ticks and xlabel. Valid options are 'top',
                   'bottom', 'bare', 'top-bare' and 'bottom-bare'.
xrotation:         Rotation angle of the xticks.
xticks:            Ticks along x-axis specified as an integer, explicit list of
                   tick locations, list of tuples containing the locations and
                   labels or a matplotlib tick locator object. If set to None
                   default matplotlib ticking behavior is applied.
yaxis:             Whether and where to display the yaxis, bare options allow suppressing
                   all axis labels including ticks and ylabel. Valid options are 'left',
                   'right', 'bare' 'left-bare' and 'right-bare'.
yrotation:         Rotation angle of the yticks.
yticks:            Ticks along y-axis specified as an integer, explicit list of
                   tick locations, list of tuples containing the locations and
                   labels or a matplotlib tick locator object. If set to None
                   default matplotlib ticking behavior is applied.
zaxis:             Whether to display the z-axis.
zrotation:         Rotation angle of the zticks.
zticks:            Ticks along z-axis specified as an integer, explicit list of
                   tick locations, list of tuples containing the locations and
                   labels or a matplotlib tick locator object. If set to None
                   default matplotlib ticking behavior is applied.
  • Operations in HoloViews are subclasses of Operation, which transform one Element or Overlay of Elements by returning a new Element that may be a transformation of the original.
  • All operations are parameterized using the param library which allows easy validation and documentation of the operation arguments. In particular, operations are instances of param.ParameterizedFunction which allows operations to be used in the same way as normal python functions.

  • This approach has several advantages, one of which is that we can manipulate the operations parameters at several different levels: at the class-level, at the instance-level or when we call it.

  • Another advantage, is that using parameterizing operations allows them to be inspected just like any other HoloViews object using hv.help . We will now do this for the histogram operation:

In [5]:
hv.help(histogram)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-0f765de31bae> in <module>()
----> 1 hv.help(histogram)

NameError: name 'histogram' is not defined
  • Above we can see a listing of all the parameters of the operation, with their defaults, the expected types and detailed docstrings for each one.
  • The histogram operation can be applied to any Element and will by default generate a histogram for the first value dimension defined on the object it is applied to.
  • As a simple example we can create an BoxWhisker Element containing samples from a normal distribution, and then apply the histogram operation to those samples in two ways:
    1) by creating an instance on which we will change the num_bins and
    2) by passing bin_range directly when calling the operation:

In [20]:
import param
import numpy as np
import holoviews as hv
from holoviews.operation import histogram

boxw = hv.BoxWhisker(np.random.randn(25000))
histop_instance = histogram.instance(num_bins=100)

boxw + histop_instance(boxw).relabel('num_bins=100') + histogram(boxw, bin_range=(0, 3)).relabel('bin_range=(0, 3)')


Out[20]:

We can see that these two ways of using operations gives us convenient control over how the parameters are applied. An instance allows us to persist some defaults which will be used in all subsequent calls, while passing keyword argument to the operations applies the parameters for just that particular call.

The third way to manipulate parameters is to set them at the class level. If we always want to use num_bins=30 instead of the default of num_bins=100 shown in the help output above, we can simply set histogram.num_binds=30 .

Operations in HoloViews are applied to individual elements, which means that when you apply an operation to a container object (such as NdLayout , GridSpace and HoloMap ) the operation is once applied per element. For an operation to work, all the elements must be of the same type which means the operation effectively acts to map the operation over all the contained elements. As a simple example we can define a HoloMap of BoxWhisker Elements by varying the width of the distribution via the Sigma value and then apply the histogram operation to it:


In [24]:
holomap = hv.HoloMap({(i*0.1+0.1): hv.BoxWhisker(np.random.randn(10000)*(i*0.1+0.1)) for i in range(5)},
                     kdims=['Sigma'])
holomap + histogram(holomap)


Out[24]:
  • For troubleshooting

In [ ]:
!pip install holoviews