如何为拼贴图中的每个组/因子设置不同的比例

时间:2016-11-10 08:53:13

标签: r ggplot2

我的代码如下所示

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

现在不是单一比例,我想为每个组分别设置渐变比例。

1 个答案:

答案 0 :(得分:2)

ggplot2内无法做到这一点,所以gridExtra拯救了!

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

为了说明不同的比例,请更改d$value[d$panel == "Group 3"] <- rnorm(36)

enter image description here

相关问题