ggplot2: Adding sample size information to x-axis tick labels

前端 未结 3 1674
慢半拍i
慢半拍i 2021-02-13 00:21

This question is related to Create custom geom to compute summary statistics and display them *outside* the plotting region (NOTE: All functions have been simplified; no error

3条回答
  •  再見小時候
    2021-02-13 00:51

    My solution might be a little simple but it works well.

    Given an example with faceting by am I start by creating labels using paste and \n.

    mtcars2 <- mtcars %>% 
      group_by(cyl, am) %>% mutate(n = n()) %>% 
      mutate(label = paste0(cyl,'\nN = ',n))
    

    I then use these labels instead of cyl in the ggplot code

    ggplot(mtcars2,
       aes(x = factor(label), y = mpg, color = factor(label))) + 
      geom_point() + 
      xlab('cyl') + 
      facet_wrap(~am, scales = 'free_x') +
      theme(legend.position = "none")
    

    To produce something like the figure below.

提交回复
热议问题