lecreprays
lecreprays

Reputation: 77

ggplot2: order bivariate points in geom_point() based on a third variable?

Consider the following simple example data, where we have two continuous variables and a third factor variable:

x<-rnorm(10)
y<-rnorm(10)

z<-as.factor(1:10)

df<-data.frame(x,y,z)

If we want to plot x vs. y, then we can have a bivariate plot such as this:

ggplot(df,aes(x,y,col=z))+geom_point(alpha=.2)+
  geom_text(data = df,label=z)

enter image description here

If for whatever reason, we wanted the points to be ordered by z, how would we do this? I.e., if we moved horizontally across the x axis, we would have z1, z2, ...,z10, regardless of the ordering of the variable x.

Upvotes: 0

Views: 101

Answers (1)

kath
kath

Reputation: 7724

You need to order your data according your criteria, before you assign the label z:

library(ggplot2)

my.df <- my.df[order(my.df$x), ] 
my.df$z <- as.factor(1:10)

ggplot(my.df, aes(x, y, col = z)) +
  geom_point(alpha = .2) +
  geom_text(aes(label = z))

enter image description here

Data

set.seed(1) # With random numbers always use set.seed for reproducibility
my.df <- data.frame(x = rnorm(10), y = rnorm(10))

Upvotes: 2

Related Questions