About
Order in Ggplot
Articles Related
Order of
Factor
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)
ggplot()+geom_point(aes(x=x,y=f))
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.
ggplot()+geom_point(aes(x=x,y=f))
Stacking of bar
The order aesthetic can change the stacking order of bar
See:
- ?aes_group_order
# Use the order aesthetic to change stacking order of bar charts
w <- ggplot(diamonds, aes(clarity, fill = cut))
w + geom_bar()
dev.new()
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)
See:
- ?aes_group_order
# Can also be used to change plot order of scatter plots
d <- ggplot(diamonds, aes(carat, price, colour = cut))
d + geom_point()
dev.new()
d + geom_point(aes(order = sample(seq_along(carat))))