Home > Net >  how to have plots from different dataframes with same x into one figure R
how to have plots from different dataframes with same x into one figure R

Time:05-25

Here I used mtcars for both plots just to reproduce an example. but actually I have df1 producing p1 and df2 producing p2. both p1 and p2 have same x axis values.

# from : http://homepages.gac.edu/~anienow2/MCS_142/R/R-barchart2-1.html
library(ggplot2) #load ggplot2 library

mtcars$gear <- factor(mtcars$gear) # Create a categorical variable
mtcars$cyl <- factor(mtcars$cyl) # Create categorical variable
p1 <- ggplot(data = mtcars, aes(x=gear, fill=cyl) )   geom_bar() # Creates stacked bar chart
p1 <- p1   xlab("Gears")   ggtitle("Cylinders by Gears") # Adds title and labels
p1




mtcars$carb <- factor(mtcars$carb)
p2 <- ggplot(data = mtcars, aes(x=gear, fill=carb) )   geom_bar() 
p2 <- p2   xlab("Gears")   ggtitle("carb") # Adds title and labels
p2

enter image description here

enter image description here

I do not want to repeat x axis. having in mind that each plot is coming from a different dataframe, I can not figure out how to apply facet_wrap or facet_grip approaches here. any Ideas?

CodePudding user response:

One way could be using:

library(grid)
grid.newpage()
grid.draw(rbind(ggplotGrob(p1  theme_minimal()   
                             theme(axis.title.x = element_blank(), axis.text.x = element_blank())), 
                ggplotGrob(p2  theme_minimal()), size = "last"))

enter image description here

  • Related