【问题标题】:Adding a single label per group in ggplot with stat_summary and text geoms使用 stat_summary 和文本几何在 ggplot 中为每个组添加一个标签
【发布时间】:2020-10-05 08:21:00
【问题描述】:

我想将计数添加到使用 stat_summary() 的 ggplot。

我遇到了要求文本向量与数据长度相同的问题。

通过下面的示例,您可以看到多次绘制的是同一个标签。

在 y 轴上设置位置的解决方法具有堆叠多个标签的效果。视觉效果有点奇怪(特别是当你有成千上万的观察时)并且对于我的目的来说不够专业。在这个问题上你必须相信我——所附的图片并没有完全传达出它的怪异之处。

我想知道是否有其他人想出了另一种方法。它适用于具有动态输入的闪亮绘图,因此不能以硬编码方式覆盖文本。

我很确定 ggplot 不是为我正在寻找的 stat_summary 的那种行为而设计的,我可能不得不放弃 stat_summary 并创建一个新的摘要数据框,但我想我会先检查其他人是否有提供一些魔法。

这是没有设置y位置的图:

library(dplyr)
library(ggplot2)


df_x <- data.frame("Group" = c(rep("A",1000), rep("B",2) ),
                   "Value" = rnorm(1002))
df_x <-  df_x %>%  
  group_by(Group) %>%
  mutate(w_count = n())
      

ggplot(df_x, aes(x = Group, y = Value)) +

    stat_summary(fun.data="mean_cl_boot", size = 1.2) +
    geom_text(aes(label = w_count)) +
    coord_flip() +
    theme_classic()


这是我的秘诀


ggplot(df_x, aes(x = Group, y = Value)) +

    stat_summary(fun.data="mean_cl_boot", size = 1.2) +
    geom_text(aes(y = 1, label = w_count)) +
    coord_flip() +
    theme_classic()

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    创建一个df_text,其中包含标签的分组信息。然后使用annotate:

    library(dplyr)
    library(ggplot2)
    
    set.seed(123)
    
    df_x <- data.frame("Group" = c(rep("A",1000), rep("B",2) ),
                       "Value" = rnorm(1002))
    
    df_text <- df_x %>% 
      group_by(Group) %>% 
      summarise(avg = mean(Value),
                n = n()) %>%
      ungroup()
    
    yoff <- 0.0
    xoff <- -0.1
    
    ggplot(df_x, aes(x = Group, y = Value)) +
      stat_summary(fun.data="mean_cl_boot", size = 1.2) +
      annotate("text", 
               x = 1:2 + xoff, 
               y = df_text$avg + yoff,
               label = df_text$n) +
      coord_flip() +
      theme_classic()
    

    【讨论】:

      【解决方案2】:

      我发现了另一种方法,当情节在其排序和过滤方面是动态的时,这种方法更加稳健,并且适用于分面。更健壮,因为它使用 stat_summary 作为文本。

      library(dplyr)
      library(ggplot2)
      
      
      df_x <- data.frame("Group" = c(rep("A",1000), rep("B",2) ),
                         "Value" = rnorm(1002))
      
      counts_df <- function(y) {
        return( data.frame( y = 1, label = paste0('n=', length(y)) ) )
      }
      
      
      ggplot(df_x, aes(x = Group, y = Value)) +
      
          stat_summary(fun.data="mean_cl_boot", size = 1.2) +
          coord_flip() +
          theme_classic()
      
      p + stat_summary(geom="text", fun.data=counts_df)
      
      

      【讨论】:

        猜你喜欢
        • 2021-06-29
        • 1970-01-01
        • 2018-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-19
        相关资源
        最近更新 更多