% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/reorder.R
\name{fct_reorder}
\alias{fct_reorder}
\alias{fct_reorder2}
\alias{last2}
\alias{first2}
\title{Reorder factor levels by sorting along another variable}
\usage{
fct_reorder(.f, .x, .fun = median, ..., .desc = FALSE)

fct_reorder2(.f, .x, .y, .fun = last2, ..., .desc = TRUE)

last2(.x, .y)

first2(.x, .y)
}
\arguments{
\item{.f}{A factor (or character vector).}

\item{.x, .y}{The levels of \code{f} are reordered so that the values
of \code{.fun(.x)} (for \code{fct_reorder()}) and \code{fun(.x, .y)} (for \code{fct_reorder2()})
are in ascending order.}

\item{.fun}{n summary function. It should take one vector for
\code{fct_reorder}, and two vectors for \code{fct_reorder2}, and return a single
value.}

\item{...}{Other arguments passed on to \code{.fun}. A common argument is
\code{na.rm = TRUE}.}

\item{.desc}{Order in descending order? Note the default is different
between \code{fct_reorder} and \code{fct_reorder2}, in order to
match the default ordering of factors in the legend.}
}
\description{
\code{fct_reorder()} is useful for 1d displays where the factor is mapped to
position; \code{fct_reorder2()} for 2d displays where the factor is mapped to
a non-position aesthetic. \code{last2()} and \code{first2()} are helpers for \code{fct_reorder2()};
\code{last2()} finds the last value of \code{y} when sorted by \code{x}; \code{first2()} finds the first value.
}
\examples{
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)
fct_reorder2(df$color, df$a, df$b)

boxplot(Sepal.Width ~ Species, data = iris)
boxplot(Sepal.Width ~ fct_reorder(Species, Sepal.Width), data = iris)
boxplot(Sepal.Width ~ fct_reorder(Species, Sepal.Width, .desc = TRUE), data = iris)

chks <- 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")
}
}
