annotate boxplot in ggplot2

后端 未结 3 2075
天涯浪人
天涯浪人 2020-12-10 08:02

I\'ve created a side-by-side boxplot using ggplot2.

p <- ggplot(mtcars, aes(x=factor(cyl), y=mpg))
p + geom_boxplot(aes(fill=factor(cyl)))
3条回答
  •  无人及你
    2020-12-10 08:07

    One way is to simply make the data.frame you need, and pass it to geom_text or geom_label:

    library(dplyr)
    
    cyl_fivenum <- mtcars %>% 
        group_by(cyl) %>% 
        summarise(five = list(fivenum(mpg))) %>% 
        tidyr::unnest()
    
    ggplot(mtcars, aes(x=factor(cyl), y=mpg)) + 
        geom_boxplot(aes(fill=factor(cyl))) + 
        geom_text(data = cyl_fivenum, 
                  aes(x = factor(cyl), y = five, label = five), 
                  nudge_x = .5)
    

提交回复
热议问题