【问题标题】:Adding total histogram count to facets in ggplot in R将总直方图计数添加到 R 中 ggplot 中的方面
【发布时间】:2020-08-05 17:51:00
【问题描述】:

我想获取一个分面直方图,并在每个图上添加文本,指示该方面的观察总数。因此,对于 carb = 1,总计数为 7,carb = 2,总计数为 10,以此类推。

p <- ggplot(mtcars, aes(x = mpg, stat = "count",fill=as.factor(carb))) + geom_histogram(bins = 8)
p <- p + facet_grid(as.factor(carb) ~ .)
p

我可以使用 table 函数来做到这一点,但对于更复杂的 faceting,我该如何快速做到这一点?

【问题讨论】:

    标签: r ggplot2 histogram facet-grid


    【解决方案1】:

    你可以试试这个。也许不是最理想的,因为您必须为标签定义xy 位置(这是在Labels 中为x 和在geom_text() 中为y 和3 完成的)。但它可以帮助你:

    #Other
    library(tidyverse)
    #Create similar data for labels
    Labels <- mtcars %>% group_by(carb) %>% summarise(N=paste0('Number is: ',n()))
    #X position
    Labels$mpg <- 25
    #Plot
    ggplot(mtcars, aes(x = mpg, stat = "count",fill=as.factor(carb))) + geom_histogram(bins = 8)+
      geom_text(data = Labels,aes(x=mpg,y=3,label=N))+facet_grid(as.factor(carb) ~ .)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-11
      相关资源
      最近更新 更多