Ggplot - Order

Ggplot Graphic Plot

About

Order in Ggplot

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)

Ggplot Scatterplot Factor Alpha Ordererd

  • 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))

Ggplot Scatterplot Factor Value Ordererd

Stacking of bar

The order aesthetic can change the stacking order of bar

See:

# 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:

# 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))))







Share this page:
Follow us:
Task Runner