-1

I want to combine two plots into one. I find way how to do it, but now they are in two row. Like this: Plots in two rows

I want them in one row. Thanks Here is my code:

library("ggplot2")
library("grid")
library("gtable")
fig1 <- ggplot(data2, aes(x=V2, y=V1))  +
  geom_boxplot(outlier.shape=NA) + 
  geom_jitter(color = "darkblue", position=position_jitter(width=.05, height=0))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        axis.title.y=element_blank())

fig2 <- ggplot(data2, aes(x=V1))  +
  geom_histogram(binwidth = 0.01)+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        axis.title.y=element_blank())

grid.draw(rbind(ggplotGrob(fig1),
                ggplotGrob(fig2),
                size = "first"))
camille
  • 16,432
  • 18
  • 38
  • 60
Franta
  • 57
  • 1
  • 7

2 Answers2

0

The patchwork package is an awesome way to do this:

library("ggplot2")
library(patchwork)

fig1 <- ggplot(data2, aes(x=V2, y=V1))  +
  geom_boxplot(outlier.shape=NA) + 
  geom_jitter(color = "darkblue", position=position_jitter(width=.05, height=0))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        axis.title.y=element_blank())

fig2 <- ggplot(data2, aes(x=V1))  +
  geom_histogram(binwidth = 0.01)+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        axis.title.y=element_blank())

fig1 + fig2

You can change the orientation easily and relative size very easily (although it will start with 2 in a row by default, so this isn't strictly needed.)

fig1 + fig2 + plot_layout(ncol = 2, width = c(1,2))
Melissa Key
  • 4,476
  • 12
  • 21
0

You had two rows because you used rbind. For two columns, you can just cbind them:

fig1 = ggplot(mtcars,aes(x=mpg,y=cyl)) + geom_point()
fig2 = ggplot(mtcars,aes(y=mpg,x=cyl,group=cyl)) + geom_boxplot()

grid.draw(cbind(ggplotGrob(fig1),ggplotGrob(fig2)))
StupidWolf
  • 45,075
  • 17
  • 40
  • 72