Boxplot show the value of mean

后端 未结 4 1815
名媛妹妹
名媛妹妹 2020-11-30 18:42

In this boxplot we can see the mean but how can we have also the number value on the plot for every mean of every box plot?

 ggplot(data=PlantGrowth, aes(x=g         


        
4条回答
  •  清歌不尽
    2020-11-30 19:23

    First, you can calculate the group means with aggregate:

    means <- aggregate(weight ~  group, PlantGrowth, mean)
    

    This dataset can be used with geom_text:

    library(ggplot2)
    ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
      stat_summary(fun.y=mean, colour="darkred", geom="point", 
                   shape=18, size=3,show_guide = FALSE) + 
      geom_text(data = means, aes(label = weight, y = weight + 0.08))
    

    Here, + 0.08 is used to place the label above the point representing the mean.

    enter image description here


    An alternative version without ggplot2:

    means <- aggregate(weight ~  group, PlantGrowth, mean)
    
    boxplot(weight ~ group, PlantGrowth)
    points(1:3, means$weight, col = "red")
    text(1:3, means$weight + 0.08, labels = means$weight)
    

提交回复
热议问题