代码之家  ›  专栏  ›  技术社区  ›  Marta Karas

ggplot:当errorbar线型为实心时,如何获取图例线型组相关

  •  4
  • Marta Karas  · 技术社区  · 8 年前

    我试图画出代表两组观察结果的线, 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)
    

    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 回复  |  直到 8 年前
        1
  •  6
  •   Marius    8 年前

    首先,您只希望线型美学应用于线条,因此不要将其包括在顶级美学贴图中,仅在 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