Ggplot - Order


Order in Ggplot

Order of


A factor is plotted ordered by its level, you can reorder it with the reorder function.

  • By default, the order is alphabetical,
f = factor(c('six','one', 'two','three','four','five'))
x = c(4,1,5,2,10,3)

The plot is not ordered by x but by the alphabet (from a to z starting at the bottom)

  • We reorder the factor by x
f <- reorder(f,x,sum) 
#  where:
#     * f is a factor of length n, 
#     * x is a vector of length n (It can also be negative if the sort must be descendant)
#     * the third parameter is a function (sum, median) that the lapply function supports.

Stacking of bar

The order aesthetic can change the stacking order of bar


# Use the order aesthetic to change stacking order of bar charts
w <- ggplot(diamonds, aes(clarity, fill = cut))
w + geom_bar()
w + geom_bar(aes(order = desc(cut)))

Point order (z-index)

The order aesthetic can be used for the plot order of point (order of appearance, not order of data)


# Can also be used to change plot order of scatter plots
d <- ggplot(diamonds, aes(carat, price, colour = cut))
d + geom_point()
d + geom_point(aes(order = sample(seq_along(carat))))

Powered by ComboStrap