reorder_within | R Documentation |
A set of functions to reorder factors within faceted groups, useful for plotting bar charts with ggplot2
.
reorder_within(x, by, within, fun = mean, sep = "___", ...)
scale_x_reordered(..., sep = "___")
scale_y_reordered(..., sep = "___")
x |
Vector to reorder. |
by |
Vector, of same length as |
within |
Vector, of same length as |
fun |
Function used within subsets to determine the ordering result ( |
sep |
Character used to separate labels for the reordering. |
... |
Additional arguments passed to |
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.
David Robinson.
David Robinson's personal package, specifically "reoder_within.R" https://github.com/dgrtwo/drlib/blob/master/R/reorder_within.R
"Ordering categories within gplot2 Facets" by Tyler Rinker: https://trinkerrstuff.wordpress.com/2016/12/23/ordering-categories-within-ggplot2-facets/
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")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.