Home > other >  Adding n and categorization next to horizontal boxplot
Adding n and categorization next to horizontal boxplot

Time:05-09

I am trying to add n= x and categories next to each horizontal boxplot and having issues with stat_n_text() function. This way both the x=n and categories aligns with the boxplot. Is there an alterative to this? I have included some code to play around with and a picture of what I am trying to achieve. Many thanks and appreciate any help.

library(patchwork)
library(ggplot2)
library(ggstance)
library(EnvStats)


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))  stat_n_text()   
  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')

Edit: Is it possible to have the axis below while deleting the legends? Thanks!

enter image description here

CodePudding user response:

I don't think stat_n_text() is what you're looking for. A simpler approach:

ltext <- diamonds %>% 
               group_by(cut) %>% 
               summarise(n=n()) %>% 
               apply(.,1,function(x) paste0(x[1]," (n=",x[2],")"))
ggplot(diamonds, aes(x=carat, y=0.5))  
            geom_boxplot(aes(fill=cut))  
            scale_fill_discrete(labels=ltext)

boxplot output with custom labels

CodePudding user response:

A combined approach to get your desired figure would be something like this:

library(patchwork)
library(ggplot2)
library(ggstance)
library(EnvStats)

p <- diamonds %>%
  group_by(cut) %>%
  mutate(cut = paste0(cut, ', n = ', n())) %>%
  ggplot(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()  
  scale_fill_viridis_d()  
  scale_y_discrete(expand = c(0, 0))  
  guides(fill = guide_legend(byrow = TRUE))  
  theme(axis.text = element_text(color = 'white'),
        axis.title = element_blank(),
        axis.line = element_blank(),
        axis.ticks = element_blank(),
        legend.key.height = unit(8, "mm"),
        legend.spacing.y = unit(0, "mm")) 
p1/p2   plot_layout(ncol = 1, nrow = 2, heights = c(2, 1))

enter image description here

  • Related