reorder_within: Reorder the levels within groups

View source: R/utils.R

reorder_withinR Documentation

Reorder the levels within groups

Description

A set of functions to reorder factors within faceted groups, useful for plotting bar charts with ggplot2.

Usage

reorder_within(x, by, within, fun = mean, sep = "___", ...)

scale_x_reordered(..., sep = "___")

scale_y_reordered(..., sep = "___")

Arguments

x

Vector to reorder.

by

Vector, of same length as x, used as reference for reordering.

within

Vector, of same length as x, used for facetting.

fun

Function used within subsets to determine the ordering result (mean by default).

sep

Character used to separate labels for the reordering.

...

Additional arguments passed to reorder for reorder_within. For scale functions, additional arguments passed to either scale_y_discrete or scale_x_discrete.

Details

First use reorder_within during aes() step for the factor level and the variable used for faceting. Then, use the scale functions (scale_xreordered, scale_y_reordered) to adjust the scale to re-order.

Author(s)

David Robinson.

Source

David Robinson's personal package, specifically "reoder_within.R" https://github.com/dgrtwo/drlib/blob/master/R/reorder_within.R

See Also

"Ordering categories within gplot2 Facets" by Tyler Rinker: https://trinkerrstuff.wordpress.com/2016/12/23/ordering-categories-within-ggplot2-facets/

Examples

library(ggplot2)
library(dplyr)
library(tidyr)

iris_gathered <- gather(iris, metric, value, -Species)

ggplot(iris_gathered, aes(reorder_within(Species, value, metric), value)) +
  geom_bar(stat = "identity") +
  scale_x_reordered() +
  facet_wrap(~ metric, scales = "free_x")

al-obrien/farrago documentation built on April 14, 2023, 6:20 p.m.