IT TIP

grid.arrange를 사용하여 플롯의 변수 목록을 어떻게 정렬합니까?

itqueen 2020. 10. 18. 19:53
반응형

grid.arrange를 사용하여 플롯의 변수 목록을 어떻게 정렬합니까?


library(ggplot2)
df <- data.frame(x=1:10, y=rnorm(10))
p1 <- ggplot(df, aes(x,y)) + geom_point()
plist <- list(p1,p1,p1,p1,p1)
# In my real example,a plot function will fit a ggplot to a list of datasets 
#and return a list of ggplots like the example above.

grid.arrange()in을 사용하여 플롯을 정렬하고 싶습니다 gridExtra.

의 플롯 수가 plist가변적 이라면 어떻게해야 합니까?

이것은 작동합니다 : grid.arrange(plist[[1]],plist[[2]],plist[[3]],plist[[4]],plist[[5]])

하지만 좀 더 일반적인 해결책이 필요합니다. 생각?


이것은 어떤가요:

library(gridExtra)
n <- length(plist)
nCol <- floor(sqrt(n))
do.call("grid.arrange", c(plist, ncol=nCol))

여기에 이미지 설명 입력


각 함수 인수를 사용하여 목록을 지정하는 한 grid.arrange()arrangeGrob()목록 함께 사용할 수 있습니다 grobs =. 예를 들어 당신이 준 예에서 :

library(ggplot2)
library(gridExtra)
df <- data.frame(x=1:10, y=rnorm(10))
p1 <- ggplot(df, aes(x,y)) + geom_point()
plist <- list(p1,p1,p1,p1,p1)

grid.arrange(grobs = plist, ncol = 2) ## display plot
ggsave(file = OutFileName, arrangeGrob(grobs = plist, ncol = 2))  ## save plot

완전성을 위해 (그리고 이미 답변 된이 오래된 질문 이 최근에 부활 됨에 따라) cowplot패키지를 사용하여 솔루션을 추가하고 싶습니다 .

cowplot::plot_grid(plotlist = plist, ncol = 2)

여기에 이미지 설명 입력


I know the question specifically states using the gridExtra package, but the wrap_plots function from the patchwork package is a great way to handle variable length list:

library(ggplot2)
# devtools::install_github("thomasp85/patchwork")
library(patchwork)

df <- data.frame(x=1:10, y=rnorm(10))
p1 <- ggplot(df, aes(x,y)) + geom_point()
plist <- list(p1,p1,p1,p1,p1)

wrap_plots(plist)

여기에 이미지 설명 입력

A useful thing about it is that you don't need to specify how many columns are required, and will aim to keep the numbers of columns and rows equal. For example:

plist <- list(p1,p1,p1,p1,p1,p1,p1,p1,p1,p1,p1,p1,p1)
wrap_plots(plist) # produces a 4 col x 4 row plot

Find out more about the patchwork package here


To fit all plots on one page you can calculate the number of columns and rows like this:

x = length(plots)

cols = round(sqrt(x),0)
rows = ceiling(x/cols)

As most multiple plotting functions have ncol and nrow as arguments you can just put these in there. I like ggarrange from ggpubr.

ggarrange(plotlist = plots, ncol=cols, nrow = rows)

This favours more rows than columns so reverse if you want the opposite. I.e. for 6 plots it will give 3 rows and 2 columns not the other way around.

참고 URL : https://stackoverflow.com/questions/10706753/how-do-i-arrange-a-variable-list-of-plots-using-grid-arrange

반응형