添加每个方面的人口中位数的hline

时间:2016-02-29 14:07:39

标签: r ggplot2 facet median

我想绘制一条水平小平面线,其中包含该方面的总体中位数。

我尝试了这种方法,但未使用以下代码创建虚拟汇总表:

require(ggplot2)

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(x = as.factor(id), y = y)) +
  geom_boxplot() +
  facet_wrap(~ gr) +
  geom_hline(aes(yintercept = median(y), group = gr), colour = 'red')

但是,为每个方面分别绘制整个数据集的中位数而不是中位数: enter image description here

过去,建议solution使用

  geom_line(stat = "hline", yintercept = "median")

但它已经停止(产生错误“No stat called StatHline”)。

另一个solution建议

 geom_errorbar(aes(ymax=..y.., ymin=..y.., y = mean))

但它会生成

Error in data.frame(y = function (x, ...)  : 
arguments imply differing number of rows: 0, 1000

最后,有一种方法可以通过创建具有所需统计数据的dummy table来绘制中位数,但我想避免使用它。

2 个答案:

答案 0 :(得分:18)

您可以在dt中为每个方面的中位数创建一个额外的列。

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')

enter image description here

答案 1 :(得分:2)

如果您不想添加具有计算出的中值的新列,则可以使用分位数回归来添加geom_smooth

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)

boxplot and median