我想将ggerrorplot
中表示平均值的点更改为水平线(类似于用于表示箱线图中的中位数的线)。我希望这条线比误差线稍粗。
在ggerrorplot
文档中没有看到这样做的选项。我是否需要做一些黑客工作,也许在ggerrorplot
之外覆盖一行?
# ToothGrowth data set available in R datasets
df <- ToothGrowth
# Examine first 10 rows
head(df, 10)
# len supp dose
# 1 4.2 VC 0.5
# 2 11.5 VC 0.5
# 3 7.3 VC 0.5
# 4 5.8 VC 0.5
# 5 6.4 VC 0.5
# 6 10.0 VC 0.5
# 7 11.2 VC 0.5
# 8 11.2 VC 0.5
# 9 5.2 VC 0.5
# 10 7.0 VC 0.5
require(ggpubr)
# Add mean, jitter points and error bars
ggerrorplot(df, x = "dose", y = "len",
add = c("mean","jitter"), error.plot= "errorbar")
答案 0 :(得分:2)
通过参数shape = 95
添加一个点层,如@hrbrmstr所示:
https://stackoverflow.com/a/39601572/8583393
p <- ggerrorplot(df, x = "dose", y = "len",
add = "jitter", # 'mean' and c() removed in this line
error.plot = "errorbar")
p + stat_summary(
geom = "point",
shape = 95,
size = 30,
col = "red",
fun.y = "mean")
我删除了在添加水平线/条时似乎不需要的pointrange层。
如果您需要控制水平线的宽度,可以使用geom_segment
。
我们首先计算y轴值
df_segment <- aggregate(len ~ dose, p$data, FUN = mean)
然后情节
p +
geom_segment(
data = transform(df_segment, dose = as.numeric(dose)),
aes(
x = dose - 0.1,
xend = dose + 0.1,
y = len,
yend = len
),
col = "red",
size = 1
)
答案 1 :(得分:1)
我的hacky解决方案是从mean
对象中获取ggplot_build
,然后使用geom_line
将所需的线添加到绘图中:
df <- ToothGrowth
require(ggplot2)
require(ggpubr)
g <- ggerrorplot(df, x = "dose", y = "len",
add = "jitter", error.plot= "errorbar")
gb <- ggplot_build(g)
g + geom_line(data=data.frame(xavg=c(t(gb$data[[2]][,c("xmin","xmax")])),
yavg=rep(gb$data[[2]]$y, each=2),
grps=rep(row.names(gb$data[[2]]),each=2)),
aes(x = xavg, y = yavg, group=grps), size=1)
由reprex package(v0.3.0)于2019-06-11创建