bar_counts | R Documentation |
Add a text layer to a bar plot with the count and percentage.
bar_counts(
data,
x,
fill,
facet,
position = c("stack", "fill"),
rev = FALSE,
fmt = "n (p%)",
...
)
data |
data set to use for plot and |
x, fill, facet |
the variables used for |
position |
a character string of |
rev |
logical; controls the reversal of text labels along the y-axis;
depending on the version of |
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 ( |
... |
additional arguments passed to |
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))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.