1

Dear Stackoverflow R Experts,

I am attempting to create a page with 9 scatterplots in a simple 3x3 layout.

Plots 1:8 are created by plot() and the 9th plot is created by ggplot().

Plots 1:8 are sized and positioned correctly for the page layout, however the 9th plot refuses to sit in the 9th location and is a full sized, separate plot.

How do I make the 9th plot sit in the correct location, properly sized, on the same page as plots 1:8?

The code (below) is a simplified example of the problem.

Any advice is greatly appreciated! Thank you

par(mfrow=c(3,3))
df<-data.frame(c(0,0))
plot(df)
plot(df)
plot(df)
plot(df)
plot(df)
plot(df)
plot(df)
plot(df)
ggplot(df)+geom_point(aes(x="",y=""))
pogibas
  • 27,303
  • 19
  • 84
  • 117
rhk123
  • 29
  • 6

1 Answers1

2

Combining base R plots and ggplots might not be the simplest task, but this is what it looks like using gridGraphics and gridExtra:

library(gridGraphics)
library(grid)
library(gridExtra)
library(ggplot2)

#save base-R plot
#taken from https://stackoverflow.com/questions/29583849/r-saving-a-plot-in-an-object
df<-data.frame(c(0,0))
plot(df)
#p <- recordPlot()
#plot.new() 
#p
grid.echo()
a <- grid.grab()
a <- editGrob(a, vp=viewport(width=unit(2,"in")), gp=gpar(fontsize=10))

#save ggplot
b <- ggplot(df)+geom_point(aes(x="",y=""))

#plot all together
grid.arrange(a, a, a, a, a, a, a, a, b, nrow = 3, ncol = 3)

enter image description here

LyzandeR
  • 37,047
  • 12
  • 77
  • 87
  • This is very helpful! Do you know how to make the 9th plot the same size as plots 1:8 ? – rhk123 Jan 03 '18 at 00:42
  • For example, if the last line of the script reorders the plots as shown below it will not work: grid.arrange(a, a, b, a, a, b, a, a, b, nrow = 3, ncol = 3) Thanks, again. – rhk123 Jan 03 '18 at 01:05
  • You are welcome. `ggplot` and `plot` use different ways of plotting graphs. It requires quite a bit of work in each individual graph to make them look nice. base-R `plot` has smaller margins for example (that's why you see them having different sizes). In reality all of them are the same size, it is just that the canvas of `ggplot` covers the whole box. I think removing the margin from `plot` and also the box along with adding a white background for ggplot will work best for you. All of the above have been answered in other questions on the site. – LyzandeR Jan 03 '18 at 09:13
  • I won't try to beautify the graphs here (this is not the question here), but it can be done given some googling (change plot margins, adding a white background to ggplot) and some work :) – LyzandeR Jan 03 '18 at 09:15
  • For example: https://stackoverflow.com/questions/5663888/trying-to-remove-all-margins-so-that-plot-region-comprises-the-entire-graphic – LyzandeR Jan 03 '18 at 09:17