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.
'IT TIP' 카테고리의 다른 글
R : 코드 블록 주석 처리 (0) | 2020.10.18 |
---|---|
CloudFront의 TTL 0은 무엇에 유용합니까? (0) | 2020.10.18 |
AngularJs에서 글로벌 http 시간 제한을 설정하는 방법 (0) | 2020.10.18 |
size_t 또는 ssize_t를 사용해야합니다. (0) | 2020.10.18 |
pip install numpy 관련 문제-RuntimeError : Broken toolchain : cannot link a simple C program (0) | 2020.10.18 |