plots generated by 'plot' and 'ggplot' side-by-side
Asked Answered
A

2

17

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.

Abruzzi answered 23/10, 2012 at 0:13 Comment(1)
you can look at the gridExtra package. It can do this I think.Snaffle
A
26

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

Agglutinative answered 23/10, 2012 at 0:53 Comment(2)
You gave a very neat answer. Thanks.Abruzzi
Where does gridFIG() come from?Vetavetch
B
2

Yes. They are both grid-based graphics systems and return graphical objects. Take a look at the grid.arrange function in gridExtra package

Beadledom answered 23/10, 2012 at 2:21 Comment(3)
Should that read If they are both grid-based graphics systems?Agglutinative
I may have been reading an earlier version that said 'lattice' and 'ggplot2' ... or this beer I'm drinking has special qualities. One of those up-votes for your answer is mine.Beadledom
plot function is not grid-based. Probably that's what you are referring to, DWin? However, I've read there are ways to embed plot into the grid system.Geognosy

© 2022 - 2024 — McMap. All rights reserved.