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

前端 未结 3 1268
一向
一向 2021-02-13 00:16

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:48

    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.

提交回复
热议问题