Home > database >  how to grid panel plots such that they have categorical variables and different x variables in ggplo
how to grid panel plots such that they have categorical variables and different x variables in ggplo

Time:10-16

My actual data is something like data below. My code is producing two separate plots like two top ones in the pic below. but I want them to be in one single plot, like the bottom plot in the pic.

data(Salaries, package = "carData")
Salaries <- Salaries[1:15,]
Salaries$name <- c("Jim","Alex","Ray","Dog","Kim",
                   "Michael","Mike","Adrian","Claire","Lucy",
                   "Fray","Lucas","Crraig","Anthony","Harper")
Salaries <- Salaries[order(Salaries$yrs.since.phd), ]
ggplot(Salaries, aes(x = yrs.since.phd , y=reorder(name, yrs.since.phd))) 
  geom_point(size = 3, aes(colour = sex)) 
  facet_grid(rows = vars(sex), scales = "free_y" ,space = "free_y") 
  theme(legend.position = "none")

Salaries <- Salaries[order(Salaries$salary), ]
ggplot(Salaries, aes(x = salary , y=reorder(name, salary))) 
  geom_point(size = 3, aes(colour = sex)) 
  facet_grid(rows = vars(sex), scales = "free_y" ,space = "free_y") 
  theme(legend.position = "none")

I m not sure how to do this. I appreciate any help with this.

enter image description here

CodePudding user response:

I hope this is your want

  library(ggplot2)
  library(gtable)
  library(grid)
  library(gridExtra)
  
  data(Salaries, package = "carData")
  Salaries <- Salaries[1:15,]
  Salaries$name <- c("Jim","Alex","Ray","Dog","Kim",
                     "Michael","Mike","Adrian","Claire","Lucy",
                     "Fray","Lucas","Crraig","Anthony","Harper")
  Salaries <- Salaries[order(Salaries$yrs.since.phd), ]
  p1=ggplot(Salaries, aes(x = yrs.since.phd , y=reorder(name, yrs.since.phd))) 
    geom_point(size = 3, aes(colour = sex)) 
    facet_grid(rows = vars(sex), scales = "free_y" ,space = "free_y") 
    theme(legend.position = "none",strip.text.y = element_blank())
  
  Salaries <- Salaries[order(Salaries$salary), ]
  p2=ggplot(Salaries, aes(x = salary , y=reorder(name, salary))) 
    geom_point(size = 3, aes(colour = sex)) 
    facet_grid(rows = vars(sex), scales = "free_y" ,space = "free_y") 
    theme(axis.text.y = element_blank(), 
          axis.ticks.y = element_blank(), 
          axis.title.y = element_blank(),
          plot.background = element_blank(),
          legend.position = "none")
  gt1 <- ggplotGrob(p1)
  gt2 <- ggplotGrob(p2)
   
  grid.arrange(gt1, gt2, ncol=2)

enter image description here

My reference comes from Getting rid of facet_grid labels on those gray boxes?.

  • Related