gpt4 book ai didi

r - 使用 ggplot2 嵌套分面图

转载 作者:行者123 更新时间:2023-12-04 12:48:31 26 4
gpt4 key购买 nike

如果我有一个嵌套因素,在这种情况下,我有多个包含在因素“订单”中的“家庭”级别,我想可能创建一个

facet_grid(Family / Order ~.)

而不是当前
facet_grid(Family + Order ~.) 

基本上——每个订单一个 strip ——旁边包含该订单内每个家庭的所有 strip 。我知道 facet_grid(Family/Order ~.) 目前是不可能的,但是我将如何实现这种效果?可以用 theme() 来完成吗?非常感谢。 --SB

我应该在上面指出家庭和秩序都是因素。数据值 B 是按物种分类的,这些物种具有它们所属的家族级别和订单级别。这是我的情节的代码:
p <- ggplot(models, aes(B,Species)) + geom_point() + facet_grid(Family + Order ~
.,scales="free",space="free")

以下是一些示例数据:
structure(list(Species = c("Acanthocyclops robustus", "Acroperus harpae", 
"Alona affinis", "Ascaphus truei", "Bosmina longirostris"), Intercept = c(-36.1182388331068,
-27.2140776216155, -25.7920464721491, -39.2233884219763, -31.4301301084581
), B = c(0.919397836908493, 0.716601987210452, 0.685455190113372,
1.04159758611351, 0.81077051300147), Bconf = c(0.407917065756464,
0.181611850119198, 0.254101713856315, 0.708582768458448, 0.234313394549538
), Order = c("Cyclopoida", "Diplostraca", "Diplostraca", "Anura",
"Diplostraca"), Family = c("Cyclopidae", "Chydoridae", "Chydoridae",
"Leiopelmatidae", "Bosminidae")), .Names = c("Species", "Intercept",
"B", "Bconf", "Order", "Family"), row.names = c(NA, 5L), class = "data.frame")

最佳答案

使用 facet_gridfacet_wrap不会构建您正在尝试构建的图形。但是,您可以构建图形列表,然后通过 gridExtra::grid.arrange 绘制它们。 .这是一个例子

library(ggplot2)
library(gridExtra)
library(dplyr)

dat <-
structure(list(Species = c("Acanthocyclops robustus", "Acroperus harpae",
"Alona affinis", "Ascaphus truei", "Bosmina longirostris"), Intercept = c(-36.1182388331068,
-27.2140776216155, -25.7920464721491, -39.2233884219763, -31.4301301084581
), B = c(0.919397836908493, 0.716601987210452, 0.685455190113372,
1.04159758611351, 0.81077051300147), Bconf = c(0.407917065756464,
0.181611850119198, 0.254101713856315, 0.708582768458448, 0.234313394549538
), Order = c("Cyclopoida", "Diplostraca", "Diplostraca", "Anura",
"Diplostraca"), Family = c("Cyclopidae", "Chydoridae", "Chydoridae",
"Leiopelmatidae", "Bosminidae")), .Names = c("Species", "Intercept",
"B", "Bconf", "Order", "Family"), row.names = c(NA, 5L), class = "data.frame")

dat

# A ggplot object with NO data. Omit the order from the facet_grid call
g <-
ggplot() +
aes(Species, B) +
geom_point() +
facet_grid(. ~ Family,
scales = "free", space = "free") +
ylim(range(dat$B)) +
xlab("")

# Build a seperate graphic for each Order and title
plots <-
lapply(unique(dat$Order), function(o) {
g %+% dplyr::filter_(dat, ~ Order == o) + ggtitle(o)
})

# build as Grobs and plot via gridExtra::grid.arrange
plots %>%
lapply(ggplotGrob) %>%
arrangeGrob(grobs = .) %>%
grid.arrange(., ncol = 1)

enter image description here

关于r - 使用 ggplot2 嵌套分面图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13651627/

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