【问题标题】:Number of Observations in ggplot Rggplot R中的观察次数
【发布时间】:2017-02-28 17:40:17
【问题描述】:

我根据我的分类特征输出响应变量的每个箱线图,但我无法突出显示每个类别的观察次数。我尝试了此处说明的 stat_summary 和 geom_text() 选项,但它们不起作用。

如何在我的箱线图中显示它们?

下面是我的代码:

    for(i in 3:ncol(Train_factor)){
    b<-paste("Boxplot for",colnames(Train_factor[i]))
    p10 <- (ggplot(data=Train_factor, aes_string(x = names(Train_factor)[i], 
    y = "Response",fill=variable)) +
    geom_boxplot())
    plot_list[[i]] = p10
    }
    for (i in 3:ncol(Train_factor)) {
    file_name = paste("boxplot", i, ".tiff", sep="")
    tiff(file_name)
    print(plot_list[[i]])
    dev.off()
    }

【问题讨论】:

    标签: r loops ggplot2


    【解决方案1】:

    您尚未提供可重现的示例,因此这里是使用内置 mtcars 数据框的通用示例。我们使用geom_text(),而不是stat="identity"(默认),我们使用stat="count"label=..count..(这是内部计算的值的数量),因此显示的值将是值的数量。

    library(ggplot2)
    
    ggplot(mtcars, (aes(x=factor(cyl), y=mpg))) +
      geom_boxplot() +
      geom_text(aes(label=..count..), y=0, stat='count', colour="red", size=4) +
      coord_cartesian(ylim=c(0,max(mtcars$mpg))) +
      theme_classic()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 2020-02-28
      • 1970-01-01
      • 2015-10-27
      • 2019-07-19
      • 2022-12-08
      • 1970-01-01
      相关资源
      最近更新 更多