gpt4 book ai didi

r - 带有 ggplot2 的 geom_raster 多面图 : control row height

转载 作者:行者123 更新时间:2023-12-05 04:15:18 24 4
gpt4 key购买 nike

在下面的示例中,我有一个包含两个实验 F1 和 F2 的数据集。基于 F1 信号进行分类,并且 F1 和 F2 值都相应地排序。在此图中,尽管行数不同(e.g 类 #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

最佳答案

使用 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()

关于r - 带有 ggplot2 的 geom_raster 多面图 : control row height,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32728421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com