【问题标题】:ggplot2: how to add sample numbers to density plot?ggplot2:如何将样本数添加到密度图?
【发布时间】:2017-08-29 16:17:28
【问题描述】:

我正在尝试生成标有样本大小的(分组)密度图。

样本数据:

set.seed(100)
df <- data.frame(ab.class = c(rep("A", 200), rep("B", 200)),
                 val = c(rnorm(200, 0, 1), rnorm(200, 1, 1)))

生成未标记的密度图,如下所示:

ggplot(df, aes(x = val, group = ab.class)) +
  geom_density(aes(fill = ab.class), alpha = 0.4)

我想要做的是在每个密度峰值附近的某处添加文本标签,显示每组中的样本数。但是,我找不到以这种方式汇总数据的正确选项组合。

我尝试将此答案中建议的代码改编为箱线图上的类似问题:https://stackoverflow.com/a/15720769/1836013

n_fun <- function(x){
  return(data.frame(y = max(x), label = paste0("n = ",length(x))))
}

ggplot(df, aes(x = val, group = ab.class)) +
  geom_density(aes(fill = ab.class), alpha = 0.4) +
  stat_summary(geom = "text", fun.data = n_fun)

但是,Error: stat_summary requires the following missing aesthetics: y 失败。

我还尝试在geom_density()stat_summary() 层的每个aes() 中添加y = ..density..,并在ggplot() 对象本身中添加...这些都没有解决问题。

我知道这可以通过为每个组手动添加标签来实现,但我希望有一个通用的解决方案,例如允许通过aes() 设置标签颜色以匹配密度。

我哪里错了?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    fun.data 返回的 y 不是 aes。 stat_summary 抱怨找不到y,如果y 的全局设置不可用,则应在ggplot(df, aes(x = val, group = ab.class, y =stat_summary(aes(y = 的全局设置中指定。 fun.data 根据通过aes 在数据中给出的y 计算在每个x 处显示点/文本/...的位置。 (我不确定我是否已经说清楚了。不是以英语为母语的人)。

    即使您指定了yaes,您也不会得到想要的结果,因为stat_summary 在每个x 上计算一个y

    但是,您可以通过geom_textannotate 将文本添加到所需位置:

    # save the plot as p
    p <- ggplot(df, aes(x = val, group = ab.class)) +
        geom_density(aes(fill = ab.class), alpha = 0.4)
    
    # build the data displayed on the plot.
    p.data <- ggplot_build(p)$data[[1]]
    
    # Note that column 'scaled' is used for plotting
    # so we extract the max density row for each group
    p.text <- lapply(split(p.data, f = p.data$group), function(df){
        df[which.max(df$scaled), ]
    })
    p.text <- do.call(rbind, p.text)  # we can also get p.text with dplyr.
    
    # now add the text layer to the plot
    p + annotate('text', x = p.text$x, y = p.text$y,
                 label = sprintf('n = %d', p.text$n), vjust = 0)
    

    【讨论】:

    • 当你想访问由 ggplot 自己计算的数据时很有用。
    猜你喜欢
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 2022-06-11
    • 2018-05-11
    相关资源
    最近更新 更多