我试图以下列方式绘制代表来自两个组y1
和y2
的观察结果的线条:
代码生成一些数据:
## generate data
x.grid <- seq(0, 1, length.out = 6)
y1.func <- function(x) 1/(x+1)
y2.func <- function(x) 2/(x+3)
set.seed(1)
x.vec <- numeric()
y.vec <- numeric()
group.vec <- numeric()
for (x in x.grid){
x.vec <- c(x.vec, rep(x, 2*10))
y.vec <- c(y.vec,
rep(y1.func(x), 10) + rnorm(10, sd = 0.1),
rep(y2.func(x), 10) + rnorm(10, sd = 0.1))
group.vec <- c(group.vec, rep("y1", 10), rep("y2", 10))
}
plt.df <- data.frame(x = x.vec, y = y.vec, group = group.vec)
## summarize data
plt.df.se <- Rmisc::summarySE(plt.df, measurevar = "y", groupvars=c("x", "group"))
方法1:
ggplot2::ggplot(plt.df.se,
aes(x = x,
y = y,
color = group,
linetype = group)) +
geom_line(position=pd, size = 0.5) +
geom_errorbar(aes(ymin=y-se, ymax=y+se), width=.05,
position=position_dodge(0.05), linetype = 1)
方法2:
ggplot2::ggplot(plt.df.se,
aes(x = x,
y = y,
color = group,
linetype = group)) +
geom_line(position=pd, size = 0.5) +
geom_errorbar(aes(ymin=y-se, ymax=y+se), width=.05,
position=position_dodge(0.05))
答案 0 :(得分:3)
首先,您只希望线型美学适用于您的线条,因此请勿将其包含在顶级美学地图中,仅限于geom_line()
。然后在show.legend = FALSE
中使用geom_errorbar()
,这样就不会影响图例:
ggplot(plt.df.se,
aes(x = x,
y = y,
color = group)) +
geom_line(aes(linetype = group), position=position_dodge(0.05), size = 0.5) +
geom_errorbar(aes(ymin=y-se, ymax=y+se), width=.05,
position=position_dodge(0.05),
show.legend = FALSE)
结果: