Combination Boxplot and Histogram using ggplot2

后端 未结 4 1380
不知归路
不知归路 2020-12-08 01:04

I am trying to combine a histogram and boxplot for visualizing a continuous variable. Here is the code I have so far

require(ggplot2)
require(gridExtra)
p1 =         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 01:35

    Using cowplot package.

    library(cowplot)
    
    #adding xlim and ylim to align axis.
    p1 = qplot(x = 1, y = mpg, data = mtcars, xlab = "", geom = 'boxplot') + 
      coord_flip() +
      ylim(min(mtcars$mpg),max(mtcars$mpg))
    
    p2 = qplot(x = mpg, data = mtcars, geom = 'histogram')+
      xlim(min(mtcars$mpg),max(mtcars$mpg))
    
    #result
    plot_grid(p1, p2, labels = c("A", "B"), align = "v",ncol = 1)
    

提交回复
热议问题