【问题标题】:How to pass a count of observations to the facet label?如何将观察计数传递给构面标签?
【发布时间】:2017-11-29 03:15:30
【问题描述】:

我想将每个方面的观察计数添加到每个方面的“标题”中。例如,我有这个:

library(tidyverse)    

mtcars %>% 
  ggplot(aes(x = cyl)) + geom_bar()+
  facet_wrap(~carb)

我想将下面函数的频率添加到每个标签

table(mtcars$carb)
 1  2  3  4  6  8 
 7 10  3 10  1  1 

因此第一行第一列的标签应该是1; n=7第一行第二列2; n=10等等...

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    使用tidyverse 的解决方案。我们可以创建一个更新的列来显示carb 的计数,然后创建一个显示更新标签的新列。

    library(tidyverse)
    
    mtcars %>% 
      group_by(carb) %>%
      mutate(carb_count = n()) %>%
      ungroup() %>%
      mutate(carb_updated = paste0(carb, "; n=", carb_count)) %>%
      ggplot(aes(x = cyl)) + geom_bar()+
      facet_wrap(~carb_updated)
    

    【讨论】:

      【解决方案2】:

      我不久前写了这个函数,用标准差、平均值或计数来标记构面。

      #' Function will update the name with the statistic of your choice
      AddNameStat <- function(df, category, count_col, stat = c("sd","mean","count"), dp= 0){
      
        # Create temporary data frame for analysis
        temp <- data.frame(ref = df[[category]], comp = df[[count_col]])
      
        # Aggregate the variables and calculate statistics
        agg_stats <- plyr::ddply(temp, "ref", summarize,
                                 sd = sd(comp),
                                 mean = mean(comp),
                                 count = length(comp))
      
        # Dictionary used to replace stat name with correct symbol for plot
        labelName <- plyr::mapvalues(stat, 
                               from=c("sd","mean","count"), 
                               to=c("\u03C3", "x", "n"))
      
        # Updates the name based on the selected variable
        agg_stats$join <- paste0(agg_stats$ref, ": ", labelName," = ",
                                 round(agg_stats[[stat]], dp))
      
        # Map the names
        name_map <- setNames(agg_stats$join, as.factor(agg_stats$ref))
        return(name_map[as.character(df[[category]])])
      }
      
      
      
      # Create a label for the facet
      mtcars$label  <- AddNameStat(mtcars, "carb", "cyl", stat = "count")
      
      mtcars %>% 
        ggplot(aes(x = cyl)) + geom_bar()+
        facet_wrap(~label)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-24
        • 1970-01-01
        • 2017-01-23
        • 2023-03-26
        • 2019-02-25
        • 2018-09-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多