首页 文章

使用stat_summary在线图上的形状

提问于
浏览
2

我确定答案非常简单,但目前它让我望而却步 . 我想使用 stat_summary() 创建一个折线图,每个x轴刻度(表示一个单独的时间点)的每个组具有不同的形状(代表实验条件) .

这是数据

set.seed(124)
ID <- rep(1:12, times = 3)
Group <- rep(c("A", "B", "C"), times = 12)
score <- rnorm(36, 25, 3)
session <- rep(c("s1","s2", "s3"), each = 12)

df <- data.frame(ID, Group, session, score)

现在我可以通过为每个时间点制作一个手段表来实现目标 . 像这样 .

gMeans <- aggregate(score ~ session + Group, data = df, mean)

然后将其绘制成图形 .

pMeans <- ggplot(data = gMeans, aes(x = session, y = score, group = Group, shape = Group)) +
  geom_line(aes(linetype = Group), size = 1) +
  geom_point(size = 5, fill = "white") +
  scale_color_hue(name = "Group", l = 30) +
  scale_shape_manual(name = "Group", values = c(23,22, 21)) +
  scale_linetype_discrete(name = "Group") +
  theme_bw() 

pMeans

但是,我希望能够跳过必须使用 stat_summary() 制作表格的步骤 . 我可以得到一个具有不同线型的类似图形,但我无法弄清楚如何在每个轴的每个轴上获得不同的形状 . 我尝试了下面的代码和 geom_point()geom_line() 的许多不同的排列,但无济于事 . 如何更改下面的代码以获得看起来像从上面的代码派生的输出的输出?

pline <- ggplot(df, aes(x=session, y=score, group = Group, shape = Group)) +
                stat_summary(fun.y="mean", geom="line", size=1.1, aes(linetype=Group, shape = Group)) +
                scale_shape_manual(values=c(1:3)) 

pline

1 回答

  • 2

    这应该有助于并清理传说:

    library(ggplot2)
    
    set.seed(124)
    ID <- rep(1:12, times = 3)
    Group <- rep(c("A", "B", "C"), times = 12)
    score <- rnorm(36, 25, 3)
    session <- rep(c("s1","s2", "s3"), each = 12)
    
    df <- data.frame(ID, Group, session, score)
    
    gg <- ggplot(df, aes(x=session, y=score, group = Group, shape = Group))
    gg <- gg + stat_summary(fun.y="mean", geom="line", size=1.1, 
                            aes(linetype = Group), show.legend=FALSE)
    gg <- gg + stat_summary(fun.y="mean", geom="point", size=5, 
                            aes(shape = Group), fill="white")
    gg <- gg + scale_shape_manual(name = "Group", values = c(23, 22, 21))
    gg <- gg + theme_bw() 
    gg <- gg + theme(legend.key=element_blank())
    gg
    

    线条被遮挡了,因此将它们保留在图例中是没有意义的 . 由于您使用 stat_summary() 作为行(vs geom_line() 与嵌入的 stat="summary" ,最好保留点geom的惯用语以及IMO) .

    enter image description here

相关问题