Add hline with population median for each facet

前端 未结 2 757
眼角桃花
眼角桃花 2020-12-17 18:06

I\'d like to plot a horizontal facet-wide line with the population median of that facet.

I tried the approach without creating a dummy summary table with the followi

相关标签:
2条回答
  • 2020-12-17 18:23

    If you don't want to add a new column with the computed median, you can add a geom_smooth using a quantile regression :

    library(ggplot2)
    library(quantreg)
    
    set.seed(1234)
    
    dt <- data.frame(gr = rep(1:2, each = 500),
                    id = rep(1:5, 2, each = 100), 
                    y = c(rnorm(500, mean = 0, sd = 1),
                          rnorm(500, mean = 1, sd = 2)))
    
    ggplot(dt, aes(y = y)) +
      geom_boxplot(aes(x = as.factor(id))) +
      geom_smooth(aes(x = id), method = "rq", formula = y ~ 1, se = FALSE) +
      facet_wrap(~ gr)
    

    0 讨论(0)
  • 2020-12-17 18:30

    You could create an extra column in dt for median per facet.

    library(dplyr) # With dplyr for example
    dt <- dt %>% group_by(gr) %>%
      mutate(med = median(y))
    
    # Rerun ggplot line with yintercept = med
    ggplot(dt, aes(x = as.factor(id), y = y)) +
      geom_boxplot() +
      facet_wrap(~ gr) +
      geom_hline(aes(yintercept = med, group = gr), colour = 'red')
    

    0 讨论(0)
提交回复
热议问题