Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set different scales for each group/factor in tile plot

Tags:

r

ggplot2

I have the code as given below

d = data.frame(sites=rep(paste("S", 1:31),each=12),
               value=runif(31*12),
               panel=c(rep("Group 1",16*12), rep("Group 2", 12*12),
                       rep("Group 3", 3*12)))


ggplot(d, aes(x = sites, y = factor(0))) + 
   geom_tile(aes(fill = value)) + 
   scale_fill_gradient(low = "green", high = "blue") +
   facet_wrap(~ panel, ncol = 1)

enter image description here

Now instead of the single scale, i want separate gradient scales for each group.

like image 694
vanathaiyan Avatar asked Nov 22 '25 09:11

vanathaiyan


1 Answers

There's no way to do that within ggplot2, so gridExtra to the rescue!

library(ggplot2)
library(gridExtra)

n <- length(unique(d$panel))
l <- vector(mode = "list", length = n)
for (i in 1:n) {
  dd <- d
  dd[d$panel!=unique(d$panel)[i], "value"] <- NA
  l[[i]] <- 
    ggplot(dd, aes(x = sites, y = 0)) + 
      geom_tile(aes(fill = value)) + 
      scale_fill_gradient(low = "green", high = "blue", na.value = NA)
}

grid.arrange(grobs = l, ncol = 1)

enter image description here

To illustrate different scales, change d$value[d$panel == "Group 3"] <- rnorm(36):

enter image description here

like image 74
tonytonov Avatar answered Nov 24 '25 01:11

tonytonov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!