2016-04-23 155 views
2

我相信答案很簡單,但目前它逃避我。我想使用stat_summary()製作折線圖,在每個x軸刻度(代表一個單獨的時間點),每個組的形狀(代表實驗條件)都有不同的形狀。圖形使用stat_summary形狀

這裏的數據

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

一個快速的方法是將功能添加到你的_point和_line調用:'ggplot(數據= DF,AES(X =會話,Y =得分,基團=集團,形狀=集團))+ geom_line(size = 5,fill =「white」,stat =「summary」,fun.y =),我們可以看到geom_line(aes(linetype = Group),size = 1,stat =「summary」,fun.y = mean)+ 意思)' – user20650

+0

謝謝你的提示@ user20650。這很有幫助,它添加了形狀,但是儘管在'geom_point'圖層中調用了'fill = white',形狀出現了黑色填充。任何想法,爲什麼這可能是? – llewmills

+0

你需要像你的例子一樣添加scale_shape('scale_shape_manual(name =「Group」,values = c(23,22,21))') – user20650

回答

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",所以最好還是保留IMO geom的成語)。

enter image description here