【问题标题】:Display mean and median on two ggplot histograms在两个 ggplot 直方图上显示平均值和中位数
【发布时间】:2020-02-10 19:11:38
【问题描述】:

我是新的 stackoverflow 用户,目前无法对原始帖子发表评论以提出问题。我遇到了以前的 stackoverflow 答案 (https://stackoverflow.com/a/34045068/11799491),我想知道如何在此图中添加两条垂直线(组的平均值和组的中位数)。

我的尝试:我不知道如何在组变量“type”中添加

geom_vline(aes(xintercept = mean(diff), ), color="black") + 
geom_vline(aes(xintercept = median(diff), ), color="red") 

【问题讨论】:

    标签: r


    【解决方案1】:

    有几种不同的方法可以做到这一点,但我喜欢创建一个单独的汇总数据框,然后将其传递给 geom_vline 调用。这使您可以分析结果并轻松添加按类型自动排序和着色的多行:

    library(tidyverse) 
    
    df <-
      tibble(
        x = rnorm(40),
        category = rep(c(0, 1), each = 20)
      )
    
    df_stats <-
      df %>% 
      group_by(category) %>% 
      summarize(
        mean = mean(x), 
        median = median(x)
      ) %>% 
      gather(key = key, value = value, mean:median)
    
    df %>% 
      ggplot(aes(x = x)) +
      geom_histogram(bins = 20) +
      facet_wrap(~ category) +
      geom_vline(data = df_stats, aes(xintercept = value, color = key))
    

    【讨论】:

      【解决方案2】:

      最简单的方法是按type 组预先计算均值和中位数。我会用aggregate 来做。

      agg <- aggregate(diff ~ type, data, function(x) {
        c(mean = mean(x), median = median(x))
      })
      agg <- cbind(agg[1], agg[[2]])
      agg <- reshape2::melt(agg, id.vars = "type")
      
      library(ggplot2)
      
      ggplot(data, aes(x = diff)) +
        geom_histogram() +
        geom_vline(data = agg, mapping = aes(xintercept = value,
                                             color = variable)) +
        facet_grid(~type) +
        theme_bw()
      

      【讨论】:

        猜你喜欢
        • 2019-04-02
        • 2012-08-31
        • 2020-08-18
        • 2019-07-20
        • 1970-01-01
        • 1970-01-01
        • 2018-11-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多