Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create faceted correlation plot using GGPLOT

Tags:

plot

r

ggplot2

I have a data frame created the following way.

library(ggplot2)

x <- data.frame(letters[1:10],abs(rnorm(10)),abs(rnorm(10)),type="x")
y <- data.frame(letters[1:10],abs(rnorm(10)),abs(rnorm(10)),type="y")
 # in reality the number of row could be larger than 10 for each x and y

all <- rbind(x,y)
colnames(all) <- c("name","val1","val2","type")

What I want to do is to create a faceted ggplot that looks roughly like this:

enter image description here

Hence each facet above is the correlation plot of the following:

# Top left facet
subset(all,type=="x")$val1 
subset(all,type=="y")$val1

# Top right facet
subset(all,type=="x")$val1 
subset(all,type=="y")$val2

# ...etc..

But I'm stuck with the following code:

p <- ggplot(all, aes(val1, val2))+ geom_smooth(method = "lm")  + geom_point() +
facet_grid(type ~ ) 
# Calculate correlation for each group
cors <- ddply(all, c(type ~ ), summarise, cor = round(cor(val1, val2), 2))
p + geom_text(data=cors, aes(label=paste("r=", cor, sep="")), x=0.5, y=0.5)

What's the right way to do it?

like image 317
neversaint Avatar asked Mar 18 '13 05:03

neversaint


1 Answers

Some of your code was incorrect. This works for me:

p <- ggplot(all, aes(val1, val2))+ geom_smooth(method = "lm")  + geom_point() +
  facet_grid(~type) 
# Calculate correlation for each group
cors <- ddply(all, .(type), summarise, cor = round(cor(val1, val2), 2))
p + geom_text(data=cors, aes(label=paste("r=", cor, sep="")), x=1, y=-0.25)

enter image description here

Edit: Following OP's comment and edit. The idea is to re-create the data with all four combinations and then facet.

# I consider the type in your previous data to be xx and yy
dat <- data.frame(val1 = c(rep(all$val1[all$type == "x"], 2), 
                           rep(all$val1[all$type == "y"], 2)), 
                  val2 = rep(all$val2, 2), 
                  grp1 = rep(c("x", "x", "y", "y"), each=10), 
                  grp2 = rep(c("x", "y", "x", "y"), each=10))

p <- ggplot(dat, aes(val1, val2)) + geom_point() + geom_smooth(method = "lm") + 
     facet_grid(grp1 ~ grp2)
cors <- ddply(dat, .(grp1, grp2), summarise, cor = round(cor(val1, val2), 2))
p + geom_text(data=cors, aes(label=paste("r=", cor, sep="")), x=1, y=-0.25)

enter image description here

like image 75
alexwhan Avatar answered Sep 30 '22 16:09

alexwhan