Density Transform¶
The density transform performs one-dimensional kernel density estimation over input data and generates a new column of samples of the estimated densities.
Here is a simple example, showing the distribution of IMDB ratings from the movies dataset:
import altair as alt
from vega_datasets import data
alt.Chart(data.movies.url).transform_density(
'IMDB_Rating',
as_=['IMDB_Rating', 'density'],
).mark_area().encode(
x="IMDB_Rating:Q",
y='density:Q',
)
The density can also be computed on a per-group basis, by specifying the groupby
argument. Here we split the above denity computation across movie genres:
import altair as alt
from vega_datasets import data
alt.Chart(
data.movies.url,
width=120,
height=80
).transform_filter(
'isValid(datum.Major_Genre)'
).transform_density(
'IMDB_Rating',
groupby=['Major_Genre'],
as_=['IMDB_Rating', 'density'],
extent=[1, 10],
).mark_area().encode(
x="IMDB_Rating:Q",
y='density:Q',
).facet(
'Major_Genre:N',
columns=4
)
Transform Options¶
The transform_density()
method is built on the
DensityTransform
class, which has the following options:
Property |
Type |
Description |
---|---|---|
as |
array(any) |
The output fields for the sample value and corresponding density estimate. Default value: |
bandwidth |
|
The bandwidth (standard deviation) of the Gaussian kernel. If unspecified or set to zero, the bandwidth value is automatically estimated from the input data using Scott’s rule. |
counts |
|
A boolean flag indicating if the output values should be probability estimates (false) or smoothed counts (true). Default value: |
cumulative |
|
A boolean flag indicating whether to produce density estimates (false) or cumulative density estimates (true). Default value: |
density |
The data field for which to perform density estimation. |
|
extent |
array(any) |
A [min, max] domain from which to sample the distribution. If unspecified, the extent will be determined by the observed minimum and maximum values of the density value field. |
groupby |
array( |
The data fields to group by. If not specified, a single group containing all data objects will be used. |
maxsteps |
|
The maximum number of samples to take along the extent domain for plotting the density. Default value: |
minsteps |
|
The minimum number of samples to take along the extent domain for plotting the density. Default value: |
steps |
|
The exact number of samples to take along the extent domain for plotting the density. If specified, overrides both minsteps and maxsteps to set an exact number of uniform samples. Potentially useful in conjunction with a fixed extent to ensure consistent sample points for stacked densities. |