stacked_dodged: Stacked and dodged bar plots

ggplot_bar_stacked_dodgedR Documentation

Stacked and dodged bar plots

Description

Utility functions for plotting stacked (on top of each other) and dodged (next to each other) bars in the same figure.

Usage

ggplot_bar_stacked_dodged(data, mapping, gap = 1)

add_stacked_dodged_xpos(data, ..., gap = 1)

calc_stacked_dodged_xlabels(data, ..., gap = 1)

Arguments

data

A data frame

mapping

An aesthetic mapping generated by ggplot2:aes, containing the aesthetics x, y, fill, and dodge. The aesthetic x will form groups on the x-axis, while dodge will form individual bars within the groups.

gap

The width of the gap between bars, relative to the width of the bars themselves (default: 1).

...

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 xpos.

Details

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.

Value

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.

Author(s)

Michaja Pehl

Examples

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')

pik-piam/quitte documentation built on April 26, 2024, 12:58 a.m.