gpt4 book ai didi

r - ggplot2 具有不同高度水平面板的平铺图

转载 作者:行者123 更新时间:2023-12-02 21:34:12 25 4
gpt4 key购买 nike

这基本上是同一个问题this one ,但有一个重要的区别:我想要一个基于 ggplot2 的图 block 图,具有水平面板,并且所有图 block 的高度相等。另一个问题是关于垂直面板。

这是一些示例代码,基于另一个问题中的代码:

d = data.frame(sites=rep(paste("S", 1:31),each=12),
month=factor(rep(1:12,31)),
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=month, y=sites, fill=value)) + 
geom_tile(colour="white") + facet_wrap(~panel, nrow=1)

结果为enter image description here

基本上,我希望每 block 蓝色瓷砖都向上移动,这样它们上面就没有空间了。我可以使用以下方法实现此目的

ggplot(d, aes(x=month, y=sites, fill=value, colour="white")) + 
geom_tile(colour="white") + facet_wrap(~panel, scales="free_y", nrow=1)

但这会导致图 block 高度不等:

enter image description here

The other question对于垂直面板有一个很好的解决方案,但是将其应用于上面的代码没有效果。水平面板有类似的解决方案吗?

最佳答案

这是使用gridExtra并设置级别的技巧:

d.splt <- split(d, d$panel)
max.unique <- max(sapply(d.splt, function(x) length(unique(x$sites))))
d.gg <- lapply(d.splt, function(d.sub){
lvls <- unique(as.character(d.sub$sites))
length(lvls) <- max.unique
lvls <- replace(lvls, is.na(lvls), "")
d.sub$sites <- factor(as.character(d.sub$sites), levels=lvls)

ggplot(d.sub, aes(x=month, y=sites, fill=value, colour="white")) +
geom_tile(colour="white", stat="identity") +
scale_y_discrete(drop=F) + scale_fill_continuous(guide=F)
} )
library(gridExtra)
do.call(grid.arrange, c(d.gg, list(nrow=1)))

enter image description here

这会引发一些警告,但您可以忽略它们。此外,您还需要添加标题和图例(您可以扰乱逻辑,以便最后一个生成图例)。

主要问题是色标将独立适合每个图表,但您可以强制修复它。

关于r - ggplot2 具有不同高度水平面板的平铺图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21761116/

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