create a boxplot in R that labels a box with the sample size (N)

后端 未结 5 983
囚心锁ツ
囚心锁ツ 2021-02-01 22:05

Is there a way to create a boxplot in R that will display with the box (somewhere) an \"N=(sample size)\"? The varwidth logical adjusts the width of the box on the basis of sam

5条回答
  •  盖世英雄少女心
    2021-02-01 22:43

    Here's some ggplot2 code. It's going to display the sample size at the sample mean, making the label multifunctional!

    First, a simple function for fun.data

    give.n <- function(x){
       return(c(y = mean(x), label = length(x)))
    }
    

    Now, to demonstrate with the diamonds data

    ggplot(diamonds, aes(cut, price)) + 
       geom_boxplot() + 
       stat_summary(fun.data = give.n, geom = "text")
    

    You may have to play with the text size to make it look good, but now you have a label for the sample size which also gives a sense of the skew.

提交回复
热议问题