ggplot_bar_stacked_dodged | R Documentation |
Utility functions for plotting stacked (on top of each other) and dodged (next to each other) bars in the same figure.
ggplot_bar_stacked_dodged(data, mapping, gap = 1)
add_stacked_dodged_xpos(data, ..., gap = 1)
calc_stacked_dodged_xlabels(data, ..., gap = 1)
data |
A data frame |
mapping |
An aesthetic mapping generated by ggplot2:aes,
containing the aesthetics |
gap |
The width of the gap between bars, relative to the width of the
bars themselves (default: |
... |
A selection of two columns. Both will be combined to form x-axis
coordinates. The first will form the outer iteration (groups), the second
the inner iteration (bars within a group). If unnamed, the column with
calculated positions will be called |
add_stacked_dodged_xpos()
adds x-axis positions to a data frame for
plotting two categorical variables within a bar plot.
calc_stacked_dodged_xlabels()
calculates matching label positions on
the x-axis.
ggplot_bar_stacked_dodged()
uses both functions to generate a plot.
add_stacked_dodged_xpos()
returns the input data frame with an
additional column. Row and column order are preserved.
calc_stacked_dodged_xlabels()
returns a named character vector for use
with ggplot2:scale_x_continuous.
ggplot_bar_stacked_dodged()
returns a ggplot2:ggplot object.
Michaja Pehl
require(tidyverse)
set.seed(0)
(data <- crossing(a = factorise(c('left', 'center', 'right')),
b = factorise(c('top', 'middle', 'bottom')),
c = letters[1:4],
d = LETTERS[25:26]) %>%
mutate(value = abs(rnorm(n())) + 0.2))
(plot.data <- add_stacked_dodged_xpos(data, c('c', 'a')))
(xlabels <- calc_stacked_dodged_xlabels(data, c('c', 'a')))
ggplot(data = plot.data) +
scale_x_continuous(breaks = xlabels) +
facet_wrap(~ d, ncol = 1, scales = 'free_x')
ggplot_bar_stacked_dodged(data, aes(x = a, y = value, fill = b, dodge = c),
gap = 1/3) +
facet_wrap(~ d, ncol = 1, scales = 'free_x')
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.