Ggplot2: building order of factors within geometry

I have a (tight) data set consisting of 5 groups, so my data.frame looks like x, y, group. I can build this data and color the points based on their group using:

p= ggplot(dataset, aes(x,y)) p = p + geom_point(aes(colour = group)) 

Now my problem is that I want to control which group is on top. At the moment, it looks like this is a random solution (at least it seems I can’t figure out what makes something a β€œtop” point). Is there any way in ggplot2 to tell geom_point what the order of the points should be?

+6
source share
2 answers

When you create a factor variable, you can influence the order using the level parameter

 f = factor(c('one', 'two'), levels = c('one', 'two')) dataset = data.frame(x=1:2, y=1:2, group=f) p = ggplot(dataset, aes(x,y)) p = p + geom_point(aes(colour = group)) 

Ggplot now uses this order for legend.

+8
source

The aesthetics of an order is what you want.

 library(ggplot2) d <- ggplot(diamonds, aes(carat, price, colour = cut)) d + geom_point() dev.new() d + geom_point(aes(order = sample(seq_along(carat)))) 

The documentation is in ?aes_group_order

+8
source

Source: https://habr.com/ru/post/911736/


All Articles