ggplot:如何获得传奇线型组依赖,而errorbar线型为实体

时间:2018-02-14 23:52:20

标签: r ggplot2 legend

我试图以下列方式绘制代表来自两个组y1y2的观察结果的线条:

  • 两组具有不同的线条颜色(在图例上标记)
  • 这两个组具有不同的线型(在图例上标记)
  • 图表有错误栏,错误栏是两个
  • 中的实线

代码生成一些数据:

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

enter image description here 糟糕:传说蓝色没有破灭

方法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))

enter image description here 错误:蓝色错误栏是虚线(我希望它们是固定的)

1 个答案:

答案 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)

结果:

enter image description here