Merge and Perfectly Align Histogram and Boxplot using ggplot2

前端 未结 1 1239
一个人的身影
一个人的身影 2020-11-27 06:39

since yesterday I am reading answers and websites in order to combine and align in one plot an histogram and a boxplot generated using ggplot

相关标签:
1条回答
  • 2020-11-27 07:09

    You can use either egg, cowplot or patchwork packages to combine those two plots. See also this answer for more complex examples.

    library(dplyr)
    library(ggplot2)
    
    plt1 <- my_df %>% select(value) %>%
      ggplot(aes(x="", y = value)) +
      geom_boxplot(fill = "lightblue", color = "black") + 
      coord_flip() +
      theme_classic() +
      xlab("") +
      theme(axis.text.y=element_blank(),
            axis.ticks.y=element_blank())
    
    plt2 <- my_df %>% select(id, value) %>%
      ggplot() +
      geom_histogram(aes(x = value, y = (..count..)/sum(..count..)),
                     position = "identity", binwidth = 1, 
                     fill = "lightblue", color = "black") +
      ylab("Relative Frequency") +
      theme_classic()
    

    egg

    # install.packages("egg", dependencies = TRUE)
    egg::ggarrange(plt2, plt1, heights = 2:1)
    

    cowplot

    # install.packages("cowplot", dependencies = TRUE)
    cowplot::plot_grid(plt2, plt1, 
                       ncol = 1, rel_heights = c(2, 1),
                       align = 'v', axis = 'lr')  
    

    patchwork

    # install.packages("devtools", dependencies = TRUE)
    # devtools::install_github("thomasp85/patchwork")
    library(patchwork)
    plt2 + plt1 + plot_layout(nrow = 2, heights = c(2, 1))
    

    0 讨论(0)
提交回复
热议问题