vanathaiyan
vanathaiyan

Reputation: 1070

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

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.

Upvotes: 3

Views: 697

Answers (1)

tonytonov
tonytonov

Reputation: 25638

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

Upvotes: 3

Related Questions