fct_reorder()
is useful for 1d displays where the factor is mapped to
position; fct_reorder2()
for 2d displays where the factor is mapped to
a non-position aesthetic. last2()
and first2()
are helpers for fct_reorder2()
;
last2()
finds the last value of y
when sorted by x
; first2()
finds the first value.
fct_reorder(.f, .x, .fun = median, ..., .desc = FALSE) fct_reorder2(.f, .x, .y, .fun = last2, ..., .desc = TRUE) last2(.x, .y) first2(.x, .y)
.f | A factor (or character vector). |
---|---|
.x, .y | The levels of |
.fun | n summary function. It should take one vector for
|
... | Other arguments passed on to |
.desc | Order in descending order? Note the default is different
between |
df <- tibble::tribble( ~color, ~a, ~b, "blue", 1, 2, "green", 6, 2, "purple", 3, 3, "red", 2, 3, "yellow", 5, 1 ) df$color <- factor(df$color) fct_reorder(df$color, df$a, min)#> [1] blue green purple red yellow #> Levels: blue red purple yellow greenfct_reorder2(df$color, df$a, df$b)#> [1] blue green purple red yellow #> Levels: purple red blue green yellowchks <- subset(ChickWeight, as.integer(Chick) < 10) chks <- transform(chks, Chick = fct_shuffle(Chick)) if (require("ggplot2")) { ggplot(chks, aes(Time, weight, colour = Chick)) + geom_point() + geom_line() # Note that lines match order in legend ggplot(chks, aes(Time, weight, colour = fct_reorder2(Chick, Time, weight))) + geom_point() + geom_line() + labs(colour = "Chick") }#>