使用stat_summary在线图上的形状

时间:2016-04-23 07:50:27

标签: r ggplot2

我确信答案非常简单,但目前它已经让我失望了。我想使用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 个答案:

答案 0 :(得分: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