class plotnine.stats.stat_density_2d(mapping: Aes | None = None, data: DataLike | None = None, **kwargs: Any)[source]

Compute 2D kernel density estimation


stat_density_2d(mapping=None, data=None, geom='density_2d',
                position='identity', na_rm=False, n=64, contour=True,
                levels=5, package='statsmodels', kde_params=None, **kwargs)

Only the mapping and data can be positional, the rest must be keyword arguments. **kwargs can be aesthetics (or parameters) used by the geom.

mappingaes, optional

Aesthetic mappings created with aes(). If specified and inherit.aes=True, it is combined with the default mapping for the plot. You must supply mapping if there is no plot mapping.


Default value


The bold aesthetics are required.

Options for computed aesthetics

'level'     # density level of a contour
'density'   # Computed density at a point
'piece'     # Numeric id of a contour in a given group

level is only relevant when contours are computed. density is available only when no contours are computed. piece is largely irrelevant.

datadataframe, optional

The data to be displayed in this layer. If None, the data from from the ggplot() call is used. If specified, it overrides the data from the ggplot() call.

geomstr or geom, optional (default: geom_density_2d)

The statistical transformation to use on the data for this layer. If it is a string, it must be the registered and known to Plotnine.

positionstr or position, optional (default: position_identity)

Position adjustment. If it is a string, it must be registered and known to Plotnine.

na_rmbool, optional (default: False)

If False, removes missing values with a warning. If True silently removes missing values.


Whether to create contours of the 2d density estimate. Default is True.

nint, optional(default: 64)

Number of equally spaced points at which the density is to be estimated. For efficient computation, it should be a power of two.

levelsint or array_like

Contour levels. If an integer, it specifies the maximum number of levels, if array_like it is the levels themselves. Default is 5.

packagestr in ['statsmodels', 'scipy', 'sklearn']

Package whose kernel density estimation to use. Default is statsmodels.


Keyword arguments to pass on to the kde class.

See also