8

I have 2 graphs, a map plotted with ggplot2 like this:

w<-ggplot()+
  geom_polygon(data=dep_shp.df, aes(x=long,y=lat,group=group,fill=classJenks))+

  #   scale_fill_gradient(limits=c(40, 100))+
  labs(title ="Classification de la proportion de producteurs par départements
       \n par la methode de jenks (2008)")+
  theme_bw()+
  coord_equal()

and a graph as object of type classIntervals from the classInt library.

I would like to put together this 2 graphs. I have tried:

vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)
grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 2)))

#creation
print(u, vp = vplayout(1, 1))
print(v, vp = vplayout(1, 2))

And something with grid.arrange

grid.arrange(plot1, plot2, ncol=2)

but none of these work.

nograpes
  • 18,623
  • 1
  • 44
  • 67
delaye
  • 1,357
  • 27
  • 45

1 Answers1

17

The method is described in the Embedding base graphics plots in grid viewports section of the gridBase vignette.

The gridBase package contains functions to set sensible parameters for the plotting region of the base plot. So we need these packages:

library(grid)
library(ggplot2)
library(gridBase)

Here's an example ggplot:

a_ggplot <- ggplot(cars, aes(speed, dist)) + geom_point()

The trick seems to be to call plot.new before you set par, otherwise it's liable to get confused and not correctly honour the settings. You also need to set new = TRUE so a new page isn't started when you call plot.

#Create figure window and layout
plot.new()
grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 2)))

#Draw ggplot
pushViewport(viewport(layout.pos.col = 1))
print(a_ggplot, newpage = FALSE)
popViewport()

#Draw bsae plot
pushViewport(viewport(layout.pos.col = 2))
par(fig = gridFIG(), new = TRUE)
with(cars, plot(speed, dist))
popViewport()
Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
  • what is the gridFIG() ?? – Antoni Mar 09 '16 at 10:07
  • 1
    @Antoni It aligns the coordinates of the base plot figure region to the current grid viewport. See `?gridBase::gridFIG`. – Richie Cotton Mar 09 '16 at 16:13
  • I do not think `grid.newpage()` is needed. When using `png` to save the plot, it produces two png files, one in blank and the other with the desired output. When removing `grid.newpage()`, just one file is created. – Erick Chacon Feb 26 '17 at 16:05