【问题标题】:ggplot2: geom_violin(), geom_text() with facet_grid() to print total number of rows in each factor excluding NAggplot2:geom_violin()、geom_text() 和 facet_grid() 打印每个因子中不包括 NA 的总行数
【发布时间】:2015-12-11 08:11:25
【问题描述】:

在下面的小提琴图中,我想添加用于绘制每个图的总行数,不包括 NA 值。

输入:

df <- cbindX(as.data.frame(rep(c(rep("trt", 4*500), rep("trt2",4*500)),2)), 
            as.data.frame(rnorm(15*500,2)), 
            as.data.frame(c(rep("A", 8*500), rep("B", 8*500))))
colnames(df) <- c("variable", "value", "mark")

代码:

ggplot(df,aes(x=variable,y=value)) + geom_violin(trim = T) + geom_text(aes(x = variable, y = -2, label=nrow(df)),color="red")

输出: 预期输出:

【问题讨论】:

    标签: r geom-text


    【解决方案1】:

    这应该可以帮助你:

    library(dplyr)
    count<-df %>% filter(!is.na(value)) %>%
    group_by(variable) %>%
    summarise(n=n()) %>%
    as.data.frame
    
    #    variable    n
    #  1      trt 4000
    #  2     trt2 3500
    
    ggplot(df,aes(x=variable,y=value)) + geom_violin(trim = T) +
    geom_text(data=count,aes(x = variable, y = -2, label=n),color="red")
    

    【讨论】:

      【解决方案2】:

      这个锻炼适合你吗

      ggplot(df,aes(x=variable,y=value)) + geom_violin(trim = T) + annotate("text", label = "4000", x =1, y = -3, size = 10, colour = "black") + annotate("text", label = "3500", x =2, y = -3, size = 10, colour = "black")
      

      【讨论】:

        猜你喜欢
        • 2013-03-29
        • 1970-01-01
        • 2019-01-16
        • 1970-01-01
        • 1970-01-01
        • 2019-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多