問題描述
用ggplot2顯示點和水平線(段)的意思 (Show means with points and horizontal lines (segments) with ggplot2)
我想繪製三組數據。具體來說,我想顯示單個數據點,包括三組的平均值。這是我到目前為止所擁有的:
library(ggplot2)
df <‑ data.frame(group=rep(c("A", "B", "C"), each=10), value=rnorm(30))
ggplot(data=df, mapping=aes(x=group, y=value)) +
geom_point() +
stat_summary(fun="mean", geom="point", color="red", size=5) +
stat_summary(fun="mean", geom="segment", mapping=aes(xend=..x.. + 0.25, yend=..y..))
這會產生下圖:
但是,我希望水平線段從每組平均值的左側開始,而不是從中心開始。我嘗試指定 mapping=aes(x=..x.. ‑ 0.25, xend=..x.. + 0.25,yend=..y..)
,但這只會給我一個錯誤:
Error: stat_summary requires the following missing aesthetics: x
我不明白為什麼我不能使用 ..x..<
參考解法
方法 1:
Try this (Maybe not the most elegant solution):
library(ggplot2)
df <‑ data.frame(group=rep(c("A", "B", "C"), each=10), value=rnorm(30))
ggplot(data=df, mapping=aes(x=group, y=value)) +
geom_point() +
stat_summary(fun="mean", geom="point", color="red", size=5) +
stat_summary(fun="mean", geom="segment", mapping=aes(xend=..x.. ‑ 0.25, yend=..y..))+
stat_summary(fun="mean", geom="segment", mapping=aes(xend=..x.. + 0.25, yend=..y..))
參考文件