Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plots generated by 'plot' and 'ggplot' side-by-side

Tags:

plot

r

ggplot2

par

Is there a way to put the plot generated by plot function and the plot by ggplot function in R in one page side-by-side?

It is easy to put plots created by the same function into one page using par or multiplot function, but I can't figure out the above question.

like image 546
Elaine Avatar asked Oct 23 '12 00:10

Elaine


People also ask

How do I plot two Ggplots next to each other?

To arrange multiple ggplot2 graphs on the same page, the standard R functions - par() and layout() - cannot be used. The basic solution is to use the gridExtra R package, which comes with the following functions: grid. arrange() and arrangeGrob() to arrange multiple ggplots on one page.

What is the difference between Ggplot and plot?

The base plotting paradigm is "ink on paper" whereas the lattice and ggplot paradigms are basically writing a program that uses the grid -package to accomplish the low-level output to the target graphics devices.

Which is better Matplotlib or Ggplot?

Both packages achieved very similar results. But the contour lines, labels, and legend in matplotlib are superior to ggplot2.


1 Answers

You can do this using the gridBase package and viewPorts.

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

# start new page
plot.new() 

# setup layout
gl <- grid.layout(nrow=1, ncol=2)
# grid.show.layout(gl)

# setup viewports
vp.1 <- viewport(layout.pos.col=1, layout.pos.row=1) 
vp.2 <- viewport(layout.pos.col=2, layout.pos.row=1) 
# init layout
pushViewport(viewport(layout=gl))
# access the first position
pushViewport(vp.1)

# start new base graphics in first viewport
par(new=TRUE, fig=gridFIG())

plot(x = 1:10, y = 10:1)

# done with the first viewport
popViewport()

# move to the next viewport
pushViewport(vp.2)

ggplotted <- qplot(x=1:10,y=10:1, 'point')
# print our ggplot graphics here
print(ggplotted, newpage = FALSE)

# done with this viewport
popViewport(1)

enter image description here

This example is a modified version of this blog post by Dylan Beaudette

like image 196
mnel Avatar answered Sep 28 '22 15:09

mnel