简体   繁体   English

在R中的一个绘图中放置多个图形(ggplot2和其他类型)

[英]Putting multiple graphs (ggplot2 and other types) in one plot in R

Is there a way of mixing ggplot2 with other type of plots (survplot, plot, etc.). 有没有一种方法可以将ggplot2与其他类型的图(survplot,plot等)混合。 I have tried par and layout but nothing seems to be appropriate. 我已经尝试过票和布局,但似乎没有什么合适的。

Thanks 谢谢

I use the function grid.arrange within the package grid.Extra 我在包grid.Extra中使用函数grid.arrange

You haven't provided sample data, but if you have 4 plots saved as "a", "b", "c" and "d", your code would be as follows: 您尚未提供示例数据,但是如果您将4个图保存为“ a”,“ b”,“ c”和“ d”,则代码如下:

     grid.arrange(a, b, c, d, nrow=2, ncol=2)

You can use "?grid.arrange" to learn more about adding additional things into your plot, like a title, the heights of the images, etc. 您可以使用“?grid.arrange”来了解有关在绘图中添加其他内容的更多信息,例如标题,图像的高度等。

     grid.arrange(a, b, c, d, nrow=4), top="YourTitleHere", heights=c(3,1,3,1))

There exist a nice function multiplot, which I have in my own standard library always loaded. 有一个不错的函数多图,我在自己的标准库中总是加载它。 It can be googled but here it is. 可以用谷歌搜索,但是在这里。

# 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.
#
library(ggplot2)
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))
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM