Add columns to a dataframe that allows building a discrete histogram. Each row will recieve a bin, bin center value, and y position. While the bin center values directly correspond to a value in the "val" unit, the y axis represents a stacking of all rows in that bin. This is designed for creating discrete histograms where each observation is a point, rather than part of a distribution.

discrete_histogram(
  data,
  val_col,
  group_cols = NULL,
  breaks = "fd",
  y_margin = 2,
  x_margin = 2
)

Arguments

data

A data.frame, data.table, or tibble.

val_col

Column name containing the value to be histogrammed, as a string.

group_cols

Column names containing any groups if faceting, as a string.

breaks

Equation or type of break to be passed to hist().

y_margin

x axis margin for space between points.

Examples

library(ggplot2)
mtcars |> discrete_histogram(
  val_col = "mpg"
) |>
  ggplot(
    aes(
      x = x_mid,
      y = y,
      label = rownames(mtcars),
      xmin = xmin,
      xmax = xmax,
      ymin = ymin,
      ymax = ymax,
      fill = cyl
    )
  ) +
  geom_vline(xintercept = 21) +
 geom_rect() +
  geom_text(
    size   = 3.5,
    colour = "white"
  )