简体   繁体   English

使用ggplot2在一个画布中使用多个图形

[英]multiple graphs in one canvas using ggplot2

I am trying to merge two ggplot2 plots into one based on this table: 我试图基于此表将两个ggplot2图合并为一个:

   Type    RatingA  RatingB
1  One     3        36
2  Two     5        53
3  One     5        57
4  One     7        74
5  Three   4        38
6  Three   8        83

I want to make two scatter plots with the mean of the ratings in the y axis and type on the x axis. 我想制作两个散点图,其中y轴的等级平均值,x轴上的类型。

This is how I create each graph: 这是我创建每个图形的方式:

p1 <- ggplot(test, aes(x=reorder(Type, RatingA, mean), y=RatingA)) +
        stat_summary(fun.y="mean", geom="point")

p2 <- ggplot(test, aes(x=reorder(Type, RatingB, mean), y=RatingB)) + 
        stat_summary(fun.y="mean", geom="point")

Since p1 and p2 have the same x axis I would like them to be ordered vertically. 由于p1和p2具有相同的x轴,我希望它们可以垂直排序。 I looked at facet_align but I couldnt find something that would do the job. 我看着facet_align,但我找不到能做到这一点的东西。

您可以在gridExtra包中使用grid.arrange() ,如下所示:

grid.arrange(p1, p2)

Julio, 胡里奥

You mention that p1 and p2 have the same x-axis, but the reordering you do based on mean does not make them the same. 你提到p1和p2具有相同的x轴,但你基于均值进行的重新排序并不能使它们相同。 p1 's axis goes "one --> two --> three" while p2 's axis goes "two --> one --> three". p1的轴变为“一 - >二 - >三”,而p2的轴变为“两 - >一 - >三”。 Is this intentional? 这是故意的吗?

Regardless, ggplot offers a few other solutions to combine these plots into one, namely colour and faceting (which you may have already tried?). 无论如何, ggplot提供了一些其他解决方案来将这些图组合成一个,即colourfaceting (您可能已经尝试过了?)。 The first step to either of these is to melt your data.frame to long format. 第一步,无论这些是melt你的data.frame长格式。 We will identify the id variable "Type" and melt assumes the rest of the columns are to be melted . 我们将识别id变量“Type”并且melt假定其余的列将被melted

test.m <- melt(test, id.var = "Type")

A quick check of the structure of the new object indicates most everything is in line, except the levels for type are a bit out of whack: 快速检查新对象的结构表明大多数都是一致的,除了类型的级别有点不明显:

> str(test.m)
'data.frame':   12 obs. of  3 variables:
 $ Type    : Factor w/ 3 levels "One","Three",..: 1 3 1 1 2 2 1 3 1 1 ...
 $ variable: Factor w/ 2 levels "RatingA","RatingB": 1 1 1 1 1 1 2 2 2 2 ...
 $ value   : int  3 5 5 7 4 8 36 53 57 74 ...

So let's rearrage the levels: 所以让我们重温水平:

test.m$Type <- factor(test.m$Type, c("One", "Three", "Two"), c("One", "Two", "Three"))

Now for the plotting. 现在为了密谋。 With colour: 有颜色:

ggplot(test.m, aes(x = Type, y = value, group = variable, colour = variable)) + 
stat_summary(fun.y = "mean", geom = "point") 

or with facets: 或与方面:

ggplot(test.m, aes(x = Type, y = value, group = variable)) + 
stat_summary(fun.y = "mean", geom = "point") +
facet_grid(variable ~ ., scales = "free")

Note I used the scales = "free" argument in the faceting so that each plot has its' own scale. 注意我在刻面中使用了scales = "free"参数,这样每个绘图都有自己的刻度。 Simply remove that argument if that's not the effect you want. 如果那不是您想要的效果,只需删除该参数即可。

this is an old question, but I recently found multiplot function, with make his job very well. 这是一个老问题,但我最近发现了multiplot函数,使他的工作非常好。

The multiplot function is from Cookbook for R: 所述multiplot功能是从食谱为R:

The function it self 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.
#
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
  require(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))
    }
  }
}

You need just source this function to your script. 您只需要将此函数提供给您的脚本即可。

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

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