2016-02-29 26 views
5

Bu faset popülasyonu ile yatay faset çapında bir çizgi çizmek istiyorum.ggplot2: her faset için popülasyon medyanı ile hline ekleyin

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

Ancak, satır her yönü için ayrı ayrı medyan yerine bütün veri kümesinin median çekilmektedir:

Aşağıdaki kod ile boş bir özeti tablo oluşturmadan yaklaşım denedi enter image description here geçmişte

, bir solution kullanmaya ileri sürülmüştür

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

ancak durduruldu ("StatHline diye bir statü yok" hatasını üretiyor).

Başka solution

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

önerdi ama orada istenilen istatistiklerle bir dummy table oluşturarak ortancasını çizmek için bir yol ama bunu önlemek istiyorum, Nihayet
Error in data.frame(y = function (x, ...) : 
arguments imply differing number of rows: 0, 1000 

üretir.

cevap

9

dt'da, her yön için medyan için fazladan bir sütun oluşturabilirsiniz.

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

İlgili konular