public bigdata

mutiple plot function 코드 뜯어 보기 본문

R programming

mutiple plot function 코드 뜯어 보기

public bigdata 2019. 9. 28. 23:55
# Multiple plot function
#
# ggplot objects can be passed in ..., or to plotlist (as a list of ggplot objects)
# - cols:   Number of columns in layout
# - layout: A matrix specifying the layout. If present, 'cols' is ignored.
#
# If the layout is something like matrix(c(1,2,3,3), nrow=2, byrow=TRUE),
# then plot 1 will go in the upper left, 2 will go in the upper right, and
# 3 will go all the way across the bottom.
#
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
  library(grid)

  # Make a list from the ... arguments and plotlist
  plots <- c(list(...), plotlist)

  numPlots = length(plots)

  # If layout is NULL, then use 'cols' to determine layout
  if (is.null(layout)) {
    # Make the panel
    # ncol: Number of columns of plots
    # nrow: Number of rows needed, calculated from # of cols
    layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
                    ncol = cols, nrow = ceiling(numPlots/cols))
  }

 if (numPlots==1) {
    print(plots[[1]])

  } else {
    # Set up the page
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))

    # Make each plot, in the correct location
    for (i in 1:numPlots) {
      # Get the i,j matrix positions of the regions that contain this subplot
      matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))

      print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                      layout.pos.col = matchidx$col))
    }
  }
}

<이해하고 내용 추가하기>

1. 여기서 ...을 list(...)을 통해서 받아야 하는 이유와 그 동작이 무엇을 의미하는지 R4ds에서도 나오지만 이해가 안됨.- advanced R을 찾아봐야 할 것 같다.

'R programming' 카테고리의 다른 글

병렬 프로그래밍  (0) 2019.11.26
ggplot tip  (0) 2019.11.07
advanced R 자료_비표준 평가 관련3  (0) 2019.09.03
%>% (R4DS 일부, help("%>%) 일부) 정리  (0) 2019.09.02
apply 계열 함수 정리하기  (0) 2019.09.01