user890739
user890739

Reputation: 733

R: Combine a graph layout with a ggplot2 object and a gplots object

I want to have one figure with two plots, one of them is a ggplot2 object, and the second is a plot generated with gplots. For example combine the next two plots in a row:

library(ggplot2)
library(gplots) #For plotmeans
df = structure(list(age = c(14, 22, 35, 21, 88, 66, 14, 22, 35, 21),
                    values = c(22, 8, 1.9, 26.8, 32, 15.,1.9, 26.8, 32, 15.)),
               .Names = c("age", "values"),
               row.names = 1:10,
               class = "data.frame")
ggplot(df, aes(values)) + geom_histogram()
plotmeans(df$values ~ df$age)

I tried grid, gridExtra, par and layout but w/o success. Any idea how can I do so?

Upvotes: 0

Views: 354

Answers (1)

user890739
user890739

Reputation: 733

I found the next solution using gridBase: (based on https://stackoverflow.com/a/14125565/890739)

library(gridBase) # To combine two plots
par(mfrow=c(1, 2))
plot.new()
vps <- baseViewports()
pushViewport(vps$figure)
vp1 <-plotViewport(c(1.8,1,0,1))
#Plot histogram
g1 <- ggplot(df, aes(values)) + geom_histogram()
print(g1,vp = vp1)
plotmeans(df$values ~ df$age)

Is there a simpler way?

Upvotes: 1

Related Questions