r - Gggplot grid.arrange all in one row 看起来像一个无缝的情节
问题描述
我正在尝试从这里实施解决方案。不幸的是,我无法上传嵌套的 facets 包并尝试通过使用 gridextra 包的解决方案来格式化 facet 标题。
但是,我似乎无法弄清楚如何将所有图表放在一行中,因为它看起来像一个单独的条形图。需要以某种方式修改这一行:grid.arrange(., ncol = 1)
. 在我的数据中,所有图的大小都相同,每个图有两个数据点。
借用的代码是:
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)
解决方案
我建议采用patchwork
一揽子方法。您可以以实用的方式定义所需的行数和列数。接下来是我们数据的代码dat
:
我们为我们的数据创建一个列表:
library(ggplot2)
library(dplyr)
library(patchwork)
#Create list
List <- split(dat,dat$Order)
我们为绘图构建一个函数:
#Now function to plot
myplotfun <- function(x)
{
G <- ggplot(x,aes(x=Family,y=B))+
geom_point() +
facet_grid(. ~ Family,
scales = "free", space = "free") +
ylim(range(x$B)) +
xlab("")+ggtitle(unique(x$Order))
return(G)
}
最后,我们使用函数应用函数和绘图patchwork
:
#Apply for plots
List2 <- lapply(List,myplotfun)
#Wrap final plot
wrap_plots(List2,nrow = 1)
输出:
您可以根据需要添加其他详细信息。
推荐阅读
- c - strncat 导致缓冲区溢出
- reactjs - 如何在firestore中同时完全删除集合文档和子集合文档
- flutter - #_currentArena 是什么?(句法)
- http - 通过 HTTP 集成从 AWS Api Gateway 中的 websocket 提取 websocket 连接 ID 和其他详细信息
- sql - 将特定列从一个表复制到另一个
- android - 用房间库中的另一个实体列填充忽略的列
- python - 使用 Getter 和 Setter 装饰器时出现 RecursionError
- c# - 案例完成后如何返回到switch语句的开头
- xcode - xcode 11.4 不适用于新的 m1 mac Big Sur(11.2.3)
- angular - ng bootstrap 模式弹出窗口不显示 ng-select