Add median population hline for every aspect

I would like to build a horizontal face with the width of the median of that face.

I tried this approach without creating a dummy summary table with the following code:

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

However, the line is drawn for the median of the entire data set instead of the median separately for each face: enter image description here

In the past, a solution has been proposed to use

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

but it was canceled (it throws an error "No stat called StatHline").

Another suggested

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

but it generates

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

Finally, there is a way to build a median by creating a dummy table with the necessary statistics, but I would like to avoid it.

+8
source share
1 answer

You can create an additional column in dt for the median for each face.

 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

+18
source

Source: https://habr.com/ru/post/1244118/


All Articles