9

All -- There are several other questions on this exact topic, but none of them addresses the problem I am facing. Here is a simple snippet of code. Can anyone advise what the issue here is please?

> grid.arrange(plot(rnorm(1000)),hist(rnorm(1000)), nrow=2, ncol=1)
Error in gList(list(wrapvp = list(x = 0.5, y = 0.5, width = 1, height = 1,  :
  only 'grobs' allowed in "gList"
Mike Wise
  • 22,131
  • 8
  • 81
  • 104
skafetaur
  • 143
  • 1
  • 1
  • 7
  • 2
    @John Coleman is right, base graphics are not `grobs`. If you really wanted to use `grid.arrange` you could try something like using the `grab_grob` function in this question. http://stackoverflow.com/questions/33826249/force-a-regular-plot-object-into-a-grob-for-use-in-grid-arrange – Mike H. Mar 12 '17 at 03:08

1 Answers1

13

The problem is that plot() and hist() are base graphics but not grid or ggplot graphics, hence they are not grobs ("grob" is a somewhat strange acronym for "grid graphical object"). You could either find equivalent grid plots or use a base graphics approach to stacking plots.

The way you would do the latter:

> par(mfrow = c(2, 1))
> plot(rnorm(1000))
> hist(rnorm(1000)) #are you sure you want to make a hist of 1000 *different* random numbers?
> par(mfrow = c(1, 1)) #reset this parameter

Output:

enter image description here

You could also consider using layout. Type ?layout for details.

John Coleman
  • 51,337
  • 7
  • 54
  • 119
  • Thank you @John Coleman! The best explanation. And no my intention with using the rnorm was just to illustrate. I have got it working using grid.arrange, but using qplot to draw the histogram. It works a treat now! – skafetaur Mar 12 '17 at 14:06
  • @skafetaur I figured that was only an example. I have actually used fairly similar examples when teaching a stats class (I'm a math teacher by trade) in which the same set of random numbers is displayed in different ways in stacked plots, so your example struck me as slightly odd. I do appreciate R's graphical powers but find the way that it is split into different incompatible packages bewildering at times. Finding a pure grid.arrange solution is probably best, but it is good to know about some of base graphic's way to make matrices of plots. – John Coleman Mar 12 '17 at 16:12