geom_raster使用ggplot2刻面图:控制行高

时间:2015-09-22 23:03:47

标签: r ggplot2 scale rows facet

在下面的例子中,我有一个包含两个实验F1和F2的数据集。基于F1信号执行分类,并且相应地对F1和F2值进行排序。在此图中,每个构面具有相​​同的尺寸,尽管行数不相同(例如类#7仅包含与其他类相比较少的元素)。我想修改代码以强制行高在整个构面上相同(因此构面将具有下面的各种空白)。任何提示将不胜感激。 谢谢

library(ggplot2)
library(reshape2)

set.seed(123)

# let's create a fake dataset
nb.experiment <- 4
n.row <- 200
n.col <- 5
nb.class <- 7

d <- matrix(round(runif(n.row * n.col),2), nc=n.col) 
colnames(d) <- sprintf("%02d", 1:5)

# These strings will be the row names of each heatmap
# in the subsequent facet plot
elements <- sample(replicate(n.row/2, rawToChar(as.raw(sample(65:90, 6, replace=T)))))


# let's create a data.frame d
d <- data.frame(d, 
                experiment = sort(rep(c("F1","F2"), n.row/2)),
                elements= elements)

# Now we split the dataset by experiments
d.split <- split(d, d$experiment)


# Now we create classes (here using hierarchical clustering )
# based on F1 experiment
dist.mat <- as.dist(1-cor(t(d.split$F1[,1:5]), method="pearson"))
hc <- hclust(dist.mat)
cuts <- cutree(hc, nb.class)
levels(cuts) <- sprintf("Class %02d", 1:nb.experiment)

# We split F1 and F2 based on classification result
for(s in names(d.split)){
  d.split[[s]] <- split(d.split[[s]], cuts)
}


# Data are melt (their is perhaps a better solution...)
# in order to use the ggplot function
dm <- melt(do.call('rbind',lapply(d.split, melt)), id.var=c( "experiment", "elements", "variable", "L1"))
dm <- dm[, -5]
colnames(dm) <- c("experiment","elements", "pos", "class", "exprs")
dm$class <- as.factor(dm$class)
levels(dm$class) <- paste("Class", levels(dm$class))

# Now we plot the data
p <- ggplot(dm, aes(x = pos, y = elements, fill = exprs))
p <- p + geom_raster()                                        
p <- p + facet_wrap(~class +experiment , scales = "free", ncol = 2)
p <- p + theme_bw()
p <- p + theme(text = element_text(size=4))
p <- p + theme(text = element_text(family = "mono", face = "bold"))

print(p)

example

1 个答案:

答案 0 :(得分:2)

使用facet_grid代替facet_wrap并设置space属性:

ggplot(dm, aes(x = pos, y = elements, fill = exprs)) +
  geom_raster() +    
  facet_grid(rowMeanClass ~ experiment , scales = "free", space = "free_y") + 
  theme_bw()