首页 文章

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

提问于
浏览
2

我试图用以下方式绘制代表两组观察的线, y1y2

  • 两组有不同的线条颜色(在图例上标注)

  • 两组有不同的线型(在图例上标注)

  • 图表有错误栏,错误栏是 both 组中的实线

代码生成一些数据:

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

Approach 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
bad :传说中的蓝色没有破灭

Approach 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
bad :蓝色错误栏是虚线(我希望它们是实心的)

1 回答

  • 3

    首先,您只需要将线型美学应用于您的线条,因此请勿将其包含在顶级美学贴图中,仅限于 geom_line() . 然后在 geom_errorbar() 中使用 show.legend = FALSE ,这样就不会影响图例:

    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

相关问题