ggplot:如何在错误条线型实体时获得图例线型组相关

Mar*_*ras 3 r legend ggplot2

我试图绘制代表两组观察结果的线条,y1y2以一种方式:

  • 两组具有不同的线条颜色(标记在图例上)
  • 两组具有不同的线型(标记在图例上)
  • 剧情有errorbar和错误酒吧是实线两个

生成一些数据的代码:

## 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"))
Run Code Online (Sandbox Code Playgroud)

方法一:

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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明 :传奇蓝没有破

方法二:

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))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明 :蓝色误差线是虚线(我希望它们是实心的)

Mar*_*ius 5

首先,您只希望将线型美学应用于您的线条,因此不要将其包含在顶级美学映射中,而仅包含在geom_line(). 然后使用show.legend = FALSEingeom_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)
Run Code Online (Sandbox Code Playgroud)

结果:

在此处输入图片说明