bar_counts: Add counts to bar plots

View source: R/ggplots.R

bar_countsR Documentation

Add counts to bar plots

Description

Add a text layer to a bar plot with the count and percentage.

Usage

bar_counts(
  data,
  x,
  fill,
  facet,
  position = c("stack", "fill"),
  rev = FALSE,
  fmt = "n (p%)",
  ...
)

Arguments

data

data set to use for plot and x, y

x, fill, facet

the variables used for x (required), fill (optional), and facet_wrap (optional - currently only facet_wrap and a single variable are supported) in the original plot

position

a character string of "stack" or "fill"; this will be the same value used in geom_bar

rev

logical; controls the reversal of text labels along the y-axis; depending on the version of ggplot, the levels of fill and order in the plot may be reversed (this was only fixed recently in ggplot)

fmt

a character string giving the format for the text; "n" and "p" will be replaced with counts and percentages, respectively; all other text will be left unchanged including newlines (\n) and percent signs; see examples

...

additional arguments passed to geom_text

Examples

mt <- within(mtcars, {
  vs <- factor(vs)
  gear <- factor(gear)
})

library('ggplot2')
ggplot(mt, aes(vs)) +
  geom_bar() +
  bar_counts(mt, vs, fmt = 'N = n', colour = 'white')

ggplot(mt, aes(vs, fill = gear)) +
  geom_bar() +
  facet_wrap(~ am) +
  bar_counts(mt, vs, gear, am, fmt = 'N = n\np%')

ggplot(mt, aes(vs, fill = gear)) +
  geom_bar(position = 'fill') +
  bar_counts(mt, vs, gear, position = 'fill',
             colour = 'white', size = 5, family = 'HersheySerif',
             fontface = 'bold.italic')


## for ggplot2 >= 2.2.0 use geom_col with pre-computed stats
dat <- data.frame(prop.table(with(mt, table(vs, gear))))
dat <- within(dat, {
  lbl <- sprintf('Gear: %s\n(%s%%)', gear, Freq * 100)
})

ggplot(dat, aes(vs, Freq, fill = gear)) +
  geom_col() +
  geom_text(aes(label = gear), position = position_stack(vjust = 0.5))

ggplot(dat, aes(vs, Freq, fill = gear)) +
  geom_col(position = 'fill') +
  geom_text(aes(label = lbl), position = position_fill(vjust = 0.5))


## or use geom_bar with stat = 'identity' and position = 'fill'
ggplot(dat, aes(vs, Freq, fill = gear)) +
  geom_bar(stat = 'identity', position = 'fill') +
  geom_text(aes(label = lbl), position = position_fill(vjust = 0.5))


raredd/plotr documentation built on Nov. 19, 2023, 4:09 a.m.