Customization#

import hvplot
import hvplot.pandas  # noqa

The hvPlot API is closely modeled on the pandas plot API but also diverges in certain cases, either to improve consistency or to provide additional functionality. This section will outline the valid options to control the axes of a plot, to control datashading and to modify the style of a plot. To look these options up interactively you may either use the tab-completion machinery in IPython or the Jupyter notebook, e.g.:

df.hvplot.line(<TAB>

OR use the help method:

hvplot.help('line')

Data Options#

The set of options for organizing, grouping, and transforming the dataset before visualization, which includes:

attr_labels (default=None): bool
    Whether to use an xarray object's attributes as labels, defaults to
    None to allow best effort without throwing a warning. Set to True
    to see warning if the attrs can't be found, set to False to disable
    the behavior.
by (default=None): str or list of str
    Dimension(s) by which to group the data categories.
    An NdOverlay is returned by default unless `subplots=True`, then an NdLayout is returned.
dynamic (default=True):
    Whether to return a dynamic plot which sends updates on widget and
    zoom/pan events or whether all the data should be embedded
    (warning: for large groupby operations embedded data can become
    very large if dynamic=False)
fields (default={}): dict
    A dictionary of fields for renaming or transforming data dimensions.
groupby (default=None): str or list
    Dimension(s) by which to group data, enabling widgets.
    Returns a DynamicMap if `dynamic=True`, else returns a HoloMap.
    See :paramref:`dynamic` for more information.
group_label (default=None): str
    Label for grouped data, typically in legends or axis labels.
kind (default='line'): str
    The type of plot to generate.
label (default=None): str
    Label for the data, typically used in the plot title or legends.
persist (default=False): boolean
    Whether to persist the data in memory when using dask.
robust: bool
    If True and clim are absent, the colormap range is computed
    with 2nd and 98th percentiles instead of the extreme values
    for image elements. For RGB elements, clips the "RGB", or
    raw reflectance values between 2nd and 98th percentiles.
    Follows the same logic as xarray's robust option.
row (default=None): str
    Column name to use for splitting the plot into separate subplots by rows.
col (default=None): str
    Column name to use for splitting the plot into separate subplots by columns.
sort_date (default=True): bool
    Whether to sort the x-axis by date before plotting
subplots (default=False): boolean
    Whether to display data in separate subplots when using the `by` parameter.
symmetric (default=None): bool
    Whether the data are symmetric around zero. If left unset, the data
    will be checked for symmetry as long as the size is less than
    ``check_symmetric_max``.
check_symmetric_max (default=1000000):
    Size above which to stop checking for symmetry by default on the data.
transforms (default={}): dict
    A dictionary of HoloViews dim transforms to apply before plotting
use_dask (default=False): boolean
    Whether to use dask for processing the data, helpful for large datasets that do not fit into memory.
use_index (default=True): boolean
    Whether to use the data's index for the x-axis by default.
    if `hover_cols == 'all', adds the index to the hover tools.
value_label (default='value'): str
    Label for the data values, typically used for the y-axis or in legends.

Resampling options#

In addition to regular plot options hvplot also exposes options for dealing with large data:

aggregator (default=None):
    Aggregator to use when applying rasterize or datashade operation
    (valid options include 'mean', 'count', 'min', 'max' and more, and
    datashader reduction objects)
datashade (default=False):
    Whether to apply rasterization and shading (colormapping) using
    the Datashader library, returning an RGB object instead of
    individual points
downsample (default=False):
    Controls the application of downsampling to the plotted data,
    which is particularly useful for large timeseries datasets to
    reduce the amount of data sent to browser and improve
    visualization performance. Requires HoloViews >= 1.16. Additional
    dependencies: Installing the `tsdownsample` library is required
    for using any downsampling methods other than the default 'lttb'.
    Acceptable values:
    - False: No downsampling is applied.
    - True: Applies downsampling using HoloViews' default algorithm
        (LTTB - Largest Triangle Three Buckets).
    - 'lttb': Explicitly applies the Largest Triangle Three Buckets
      algorithm.
    - 'minmax': Applies the MinMax algorithm, selecting the minimum
      and maximum values in each bin. Requires `tsdownsample`.
    - 'm4': Applies the M4 algorithm, selecting the minimum, maximum,
      first, and last values in each bin. Requires `tsdownsample`.
    - 'minmax-lttb': Combines MinMax and LTTB algorithms for
      downsampling, first applying MinMax to reduce to a preliminary
      set of points, then LTTB for further reduction. Requires
      `tsdownsample`.
    Other string values corresponding to supported algorithms in
    HoloViews may also be used.
dynspread (default=False):
    For plots generated with datashade=True or rasterize=True,
    automatically increase the point size when the data is sparse
    so that individual points become more visible
max_px (default=3): int
    The maximum size in pixels for dynamically spreading elements in sparse data using `dynspread`.
    This helps to increase the visibility of sparse data points.
pixel_ratio (default=None):
   Pixel ratio applied to the height and width, used when rasterizing or
   datashading. When not set explicitly, the ratio is automatically
   obtained from the browser device pixel ratio. Default is 1 when
   the browser information is not available. Useful when the browser
   information is not available (pixel_ratio=2 can give better results on
   Retina displays) or for using lower resolution for speed.
precompute (default=False): boolean
    Whether to precompute aggregations when using `rasterize` or `datashade`.
rasterize (default=False):
    Whether to apply rasterization using the Datashader library,
    returning an aggregated Image (to be colormapped by the
    plotting backend) instead of individual points
resample_when (default=None):
    Applies a resampling operation (datashade, rasterize or downsample) if
    the number of individual data points present in the current zoom range
    is above this threshold. The raw plot is displayed otherwise.
threshold (default=0.5): float
    When using `dynspread`, this value defines the minimum density of overlapping points
    required before the spreading operation is applied.
    Values between 0 and 1, where 1 means always spread and 0 means never spread.
x_sampling/y_sampling (default=None):
    Specifies the smallest allowed sampling interval along the x/y axis.
    Used when rasterizing or datashading.

Geographic options#

When dealing with geographic data, there are a number of options that become available. See the geographic section for more information on working with geographic data:

coastline (default=False):
    Whether to display a coastline on top of the plot, setting
    coastline='10m'/'50m'/'110m' specifies a specific scale.
crs (default=None):
    Coordinate reference system of the data (input projection) specified as a string or integer EPSG code,
    a CRS or Proj pyproj object, a Cartopy CRS object or class name, a WKT string, or a proj.4 string.
    Defaults to PlateCarree.
features (default=None): dict or list
    A list of features or a dictionary of features and the scale
    at which to render it. Available features include 'borders',
    'coastline', 'lakes', 'land', 'ocean', 'rivers' and 'states'.
    Available scales include '10m'/'50m'/'110m'.
geo (default=False):
    Whether the plot should be treated as geographic (and assume
    PlateCarree, i.e. lat/lon coordinates).
global_extent (default=False):
    Whether to expand the plot extent to span the whole globe.
project (default=False):
    Whether to project the data before plotting (adds initial
    overhead but avoids projecting data when plot is dynamically
    updated).
projection (default=None):
    Coordinate reference system of the plot (output projection) specified as a string or integer EPSG code,
    a CRS or Proj pyproj object, a Cartopy CRS object or class name, a WKT string, or a proj.4 string.
    Defaults to PlateCarree.
tiles (default=False):
    Whether to overlay the plot on a tile source.
    If coordinate values fall within lat/lon bounds, auto-projects to EPSG:3857
    unless `projection=False` or if the data is lazily loaded (dask / ibis).
    Tiles sources can be selected by name or a tiles object or class can be passed,
    the default is 'Wikipedia'.
tiles_opts (default=None): dict
    Options to customize the tiles layer created when `tiles` is set,
    e.g. `dict(alpha=0.5)`.

Size and Layout options#

These are customization options for plot sizes and overall layout, including responsive mode:

fontscale: number
    Scales the size of all fonts by the same amount, e.g. fontscale=1.5
    enlarges all fonts (title, xticks, labels etc.) by 50%
frame_width/frame_height: int
    The width and height of the data area of the plot
max_width/max_height: int
    The maximum width and height of the plot for responsive modes
min_width/min_height: int
    The minimum width and height of the plot for responsive modes
width (default=700)/height (default=300): int
    The width and height of the plot in pixels
padding: number or tuple
    Fraction by which to increase auto-ranged extents to make
    datapoints more visible around borders. Supports tuples to
    specify different amount of padding for x- and y-axis and
    tuples of tuples to specify different amounts of padding for
    upper and lower bounds.
responsive: boolean
    Whether the plot should responsively resize depending on the
    size of the browser. Responsive mode will only work if at
    least one dimension of the plot is left undefined, e.g. when
    width and height or width and aspect are set the plot is set
    to a fixed size, ignoring any responsive option.

Axis options#

There are also options for customizing axis appearance and behavior, including labels, limits, tick formatting, and axis scaling:

aspect (default=None): str or float
    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 specifying the ratio between plot
    width and height may also be passed. To control the aspect
    ratio between the axis scales use the `data_aspect` option
    instead.
data_aspect (default=None): float
    Defines the aspect of the axis scaling, i.e. the ratio of
    y-unit to x-unit.
autorange (default=None): Literal['x', 'y'] | None
    Whether to enable auto-ranging along the x- or y-axis when
    zooming. Requires HoloViews >= 1.16.
flip_xaxis/flip_yaxis: boolean
    Whether to flip the axis left to right or up and down respectively
framewise (default=True): boolean
    Whether to compute the axis ranges frame-by-frame when using dynamic plots.
invert (default=False): boolean
    Swaps x- and y-axis
logx/logy (default=False): boolean
    Enables logarithmic x- and y-axis respectively
logz (default=False): boolean
    Enables logarithmic colormapping
loglog (default=False): boolean
    Enables logarithmic x- and y-axis
rot: number
    Rotates the axis ticks along the x-axis by the specified
    number of degrees.
shared_axes (default=True): boolean
    Whether to link axes between plots
subcoordinate_y: bool or dict
   Whether to enable sub-coordinate y systems for this plot. Accepts also a
   dictionary of related options to pass down to HoloViews,
   e.g. `{'subcoordinate_scale': 2}`.
title (default=''): str
    Title for the plot
xaxis/yaxis: str or None
    Whether to show the x/y-axis and whether to place it at the
    'top'/'bottom' and 'left'/'right' respectively.
xformatter/yformatter (default=None): str or TickFormatter
    Formatter for the x-axis and y-axis (accepts printf formatter,
    e.g. '%.3f', and bokeh TickFormatter)
xlabel/ylabel/clabel (default=None): str
    Axis labels for the x-axis, y-axis, and colorbar
xlim/ylim (default=None): tuple or list
    Plot limits of the x- and y-axis
xticks/yticks/cticks (default=None): int or list
    Ticks along x-axis, y-axis, and colorbar specified as an integer, list of
    ticks positions, or list of tuples of the tick positions and labels

Grid and Legend options#

Options for setting the grid or legend of plots as well as colorbar options:

colorbar (default=False): boolean
    Enables a colorbar
grid (default=False): boolean
    Whether to show a grid
legend (default=True): boolean or str
    Whether to show a legend, or a legend position
    ('top', 'bottom', 'left', 'right')

Interactivity options#

Bokeh specific options for adding hover tools as well as other interactive tools like tap tool and box select tool:

hover : boolean
    Whether to show hover tooltips, default is True unless datashade is
    True in which case hover is False by default
hover_cols (default=[]): list or str
    Additional columns to add to the hover tool or 'all' which will
    includes all columns (including indexes if use_index is True).
hover_formatters:
    A dict of formatting options for the hover tooltip.
hover_tooltips: list[str] or list[tuple]
    A list of dimensions to be displayed in the hover tooltip.
tools (default=[]): list
    List of tool instances or strings (e.g. ['tap', 'box_select'])

Kind options#

Each type of plot may have a number of options to visual attributes specific to that plot type. In general these are provided in the docstring of the plot type, which can be viewed using help method:

hvplot.help('scatter', generic=False, style=False)
The `scatter` plot visualizes your points as markers in 2D space. You can visualize
one more dimension by using colors.

The `scatter` plot is a good first way to plot data with non continuous axes.

Reference: https://hvplot.holoviz.org/reference/tabular/scatter.html

Parameters
----------
x : string, optional
    Field name(s) to draw x-positions from. If not specified, the index is
    used. Can refer to continuous and categorical data.
y : string or list, optional
    Field name(s) to draw y-positions from. If not specified, all numerical
    fields are used.
marker : string, optional
    The marker shape specified above can be any supported by matplotlib, e.g. s, d, o etc.
    See https://matplotlib.org/stable/api/markers_api.html.
c : string, optional
    A color or a Field name to draw the color of the marker from
s : int, optional, also available as 'size'
    The size of the marker
by : string, optional
    A single field or list of fields to group by. All the subgroups are visualized.
groupby: string, list, optional
    A single field or list of fields to group and filter by. Adds one or more widgets to
    select the subgroup(s) to visualize.
scale: number, optional
    Scaling factor to apply to point scaling.
logz : bool
    Whether to apply log scaling to the z-axis. Default is False.
color : str or array-like, optional.
    The color for each of the series. Possible values are:

    A single color string referred to by name, RGB or RGBA code, for instance 'red' or
    '#a98d19.

    A sequence of color strings referred to by name, RGB or RGBA code, which will be used
    for each series recursively. For instance ['green','yellow'] each field’s line will be
    filled in green or yellow, alternatively. If there is only a single series to be
    plotted, then only the first color from the color list will be used.
**kwds : optional
    Additional keywords arguments are documented in `hvplot.help('scatter')`.

Returns
-------
A Holoviews object. You can `print` the object to study its composition and run

.. code-block::

    import holoviews as hv
    hv.help(the_holoviews_object)

to learn more about its parameters and options.

Example
-------

.. code-block::

    import hvplot.pandas
    import pandas as pd

    df = pd.DataFrame(
        {
            "actual": [100, 150, 125, 140, 145, 135, 123],
            "forecast": [90, 160, 125, 150, 141, 141, 120],
            "numerical": [1.1, 1.9, 3.2, 3.8, 4.3, 5.0, 5.5],
            "date": pd.date_range("2022-01-03", "2022-01-09"),
            "string": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        },
    )
    scatter = df.hvplot.scatter(
        x="numerical",
        y=["actual", "forecast"],
        ylabel="value",
        legend="bottom",
        height=500,
        color=["#f16a6f", "#1e85f7"],
        size=100,
    )
    scatter

You can overlay the `scatter` markers on for example a `line` plot

.. code-block::

    line = df.hvplot.line(
        x="numerical", y=["actual", "forecast"], color=["#f16a6f", "#1e85f7"], line_width=5
    )
    scatter * line

References
----------

- Bokeh: https://docs.bokeh.org/en/latest/docs/user_guide/plotting.html#scatter-markers
- HoloViews: https://holoviews.org/reference/elements/matplotlib/Scatter.html
- Pandas: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.scatter.html
- Plotly: https://plotly.com/python/line-and-scatter/
- Matplotlib:  https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.scatter.html
- Seaborn: https://seaborn.pydata.org/generated/seaborn.scatterplot.html
- Wiki: https://en.wikipedia.org/wiki/Scatter_plot

Styling options#

Beyond the options specific to each plot type (or kind) it is also possible to customize each component in detail, exposing all the options bokeh exposes. These usually include options to color the line and fill color, alpha and style. To see the full listing we can once again use the help method:

hvplot.help('line', docstring=False, generic=False)
Style options
-------------
alpha
color
hover_alpha
hover_color
hover_line_alpha
hover_line_cap
hover_line_color
hover_line_dash
hover_line_dash_offset
hover_line_join
hover_line_width
line_alpha
line_cap
line_color
line_dash
line_dash_offset
line_join
line_width
muted
muted_alpha
muted_color
muted_line_alpha
muted_line_cap
muted_line_color
muted_line_dash
muted_line_dash_offset
muted_line_join
muted_line_width
nonselection_alpha
nonselection_color
nonselection_line_alpha
nonselection_line_cap
nonselection_line_color
nonselection_line_dash
nonselection_line_dash_offset
nonselection_line_join
nonselection_line_width
selection_alpha
selection_color
selection_line_alpha
selection_line_cap
selection_line_color
selection_line_dash
selection_line_dash_offset
selection_line_join
selection_line_width
visible

In general, the objects returned by hvPlot are regular HoloViews objects, which can be overlaid, laid out, composed and customized like all other HoloViews objects. The HoloViews website explains all the functionality available, but what’s on this hvPlot website should be enough to get you up and running for typical usage.

This web page was generated from a Jupyter notebook and not all interactivity will work on this website.