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')
Generic options#
The generic set of options which may apply to all plot types include:
bgcolor: str
Background color of the data area of the plot
clim: tuple
Lower and upper bound of the color scale
cnorm (default='linear'): str
Color scaling which must be one of 'linear', 'log' or 'eq_hist'
colorbar (default=False): boolean
Enables a colorbar
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%
fontsize: number or dict
Set title, label and legend text to the same fontsize. Finer control
by using a dict: {'title': '15pt', 'ylabel': '5px', 'ticks': 20}
flip_xaxis/flip_yaxis: boolean
Whether to flip the axis left to right or up and down respectively
grid (default=False): boolean
Whether to show a grid
hover: boolean or Literal["vline", "hline"]
Whether to show hover tooltips, default is True unless datashade is
True in which case hover is False by default. Can also set
`vline` for hitbox across a vertical line or `hline` for hitbox across a horizontal line.
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. See
[HoloViews docs](https://holoviews.org/user_guide/Plotting_with_Bokeh.html#hover-tools)
or [Bokeh docs](https://docs.bokeh.org/en/latest/docs/user_guide/interaction/tools.html#hovertool)
for more info on structuring.
invert (default=False): boolean
Swaps x- and y-axis
frame_width/frame_height: int
The width and height of the data area of the plot
legend (default=True): boolean or str
Whether to show a legend, or a legend position
('top', 'bottom', 'left', 'right')
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
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
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.
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.
rot: number
Rotates the axis ticks along the x-axis by the specified
number of degrees.
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}`.
shared_axes (default=True): boolean
Whether to link axes between plots
transforms (default={}): dict
A dictionary of HoloViews dim transforms to apply before plotting
title (default=''): str
Title for the plot
tools (default=[]): list
List of tool instances or strings (e.g. ['tap', box_select'])
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
width (default=700)/height (default=300): int
The width and height of the plot in pixels
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.
sort_date (default=True): bool
Whether to sort the x-axis by date before plotting
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.
Datashading 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)
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.
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)
datashade (default=False):
Whether to apply rasterization and shading using datashader
library returning an RGB object
dynspread (default=False):
Allows plots generated with datashade=True to increase the point
size to make sparse regions more visible
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.
rasterize (default=False):
Whether to apply rasterization using the datashader library
returning an aggregated Image
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.
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)`.
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.