5
我想繪製一個水平方位範圍的人口與該方面的人口中位數。ggplot2:爲每個方面添加帶人口中位數的hline
我想盡了辦法,而不與下面的代碼創建一個虛擬彙總表:
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')
然而,線被繪製爲整個數據集,而不是中值分別爲每個小面的中值:
在過去,一個solution已建議使用
geom_line(stat = "hline", yintercept = "median")
但它已經停止(產生錯誤「沒有Stat Statline」)。
另一個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繪製中位數,但我想,以避免它。