Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

density_bins

Density bins and histogram bins as data frames


Description

Generates a data frame of bins representing the kernel density (or histogram) of a vector, suitable for use in generating predictive distributions for visualization. These functions were originally designed for use with the now-deprecated predict_curve(), and may be deprecated in the future.

Usage

density_bins(x, n = 101, ...)

histogram_bins(x, n = 30, breaks = n, ...)

Arguments

x

A numeric vector

n

Number of bins

...

Additional arguments passed to density() or hist().

breaks

Used to set bins for histogram_bins. Can be number of bins (by default it is set to the value of n) or a method for setting bins. See the breaks argument of hist().

Details

These functions are simple wrappers to density() and hist() that compute density estimates and return their results in a consistent format: a data frame of bins suitable for use with the now-deprecated predict_curve().

density_bins computes a kernel density estimate using density().

histogram_bins computes a density histogram using hist().

Value

A data frame representing bins and their densities with the following columns:

mid

Bin midpoint

lower

Lower endpoint of each bin

upper

Upper endpoint of each bin

density

Density estimate of the bin

Author(s)

Matthew Kay

See Also

See add_predicted_draws() and stat_lineribbon() for a better approach. These functions may be deprecated in the future.

Examples

library(ggplot2)
library(dplyr)
library(purrr)
library(tidyr)

if (
  require("brms", quietly = TRUE) &&
  require("modelr", quietly = TRUE)
) {

  theme_set(theme_light())

  m_mpg = brm(mpg ~ hp * cyl, data = mtcars)

  step = 1
  mtcars %>%
    group_by(cyl) %>%
    data_grid(hp = seq_range(hp, by = step)) %>%
    add_predicted_draws(m_mpg) %>%
    summarise(densities = list(density_bins(.prediction))) %>%
    unnest(densities) %>%
    ggplot() +
    geom_rect(aes(
      xmin = hp - step/2, ymin = lower, ymax = upper, xmax = hp + step/2,
      fill = ordered(cyl), alpha = density
    )) +
    geom_point(aes(x = hp, y = mpg, fill = ordered(cyl)), shape = 21, data = mtcars) +
    scale_alpha_continuous(range = c(0, 1)) +
    scale_fill_brewer(palette = "Set2")
}

tidybayes

Tidy Data and 'Geoms' for Bayesian Models

v2.3.1
GPL (>= 3)
Authors
Matthew Kay [aut, cre], Timothy Mastny [ctb]
Initial release
2020-10-30

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.