问题描述
我正在尝试从here实施解决方案。不幸的是,我无法上载嵌套的构面软件包,并无法尝试通过使用gridextra软件包来格式化构面标题。
但是,我似乎无法弄清楚该怎么做,就是将所有图形都放在一行上,因为它看起来就像是一张条形图。需要以某种方式修改此行: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","Anura","Diplostraca"),Family = c("Cyclopidae","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)
输出:
您可以根据需要添加其他详细信息。