Home > other >  Adding Box plot below x axis
Adding Box plot below x axis

Time:05-09

I have the code below and was wondering if there's a way to have the box plot below the the x-axis or another package. Or have the box plot below the x-axis in general with a white background. Thanks!

library(ggstance)
library(ggplot2)

ggplot(diamonds, aes(x = carat, y = -0.5))  
  
  # horizontal box plot
  geom_boxploth(aes(fill = cut))  
  
  # normal density plot
  geom_density(aes(x = carat), inherit.aes = FALSE)  
  

  # reproduce original chart's color scale (o/w ordered factors will result
  # in viridis scale by default, using the current version of ggplot2)
  scale_fill_discrete()

enter image description here

CodePudding user response:

You could use the patchwork package:

library(patchwork)

 p <- ggplot(diamonds, aes(x = carat, y = -0.5))
 
 p1 <- p   geom_density(aes(x = carat), inherit.aes = FALSE) 
 p2 <- p   geom_boxploth(aes(fill = cut))  
       theme_classic()  
       theme(axis.text = element_text(color = 'white'),
             axis.title = element_blank(),
             axis.line = element_blank(),
             axis.ticks = element_blank())
 p1/p2   plot_layout(ncol = 1, nrow = 2, heights = c(2, 1),
                     guides = 'collect')

enter image description here

  • Related