2016-04-14 69 views
3

「a」是一個數據幀。用ggplot2連接不同線型的點

set.seed(2) 
a<-data.frame(group= rep(c("A","B","C"),each=4),factor=rep(c(1,1,2,2),3), 
       model=rep(c("old","new"),6),mean=runif(12),sd=runif(12)/10) 

>a 
      group factor model  mean   sd 
     1  A  1 old 0.1848823 0.076051331 
     2  A  1 new 0.7023740 0.018082010 
     3  A  2 old 0.5733263 0.040528218 
     4  A  2 new 0.1680519 0.085354845 
     5  B  1 old 0.9438393 0.097639849 
     6  B  1 new 0.9434750 0.022582546 
     7  B  2 old 0.1291590 0.044480923 
     8  B  2 new 0.8334488 0.007497942 
     9  C  1 old 0.4680185 0.066189876 
     10  C  1 new 0.5499837 0.038754954 
     11  C  2 old 0.5526741 0.083688918 
     12  C  2 new 0.2388948 0.015050144 

我想用ggplot2繪製一個「mean±sd」線圖。 我的目的是繪製一張圖片(x軸是「group」,y軸是「mean±sd」,不同的「factor」應該有不同的顏色,不同的「model」應該有不同的連接線型虛線,新的模式是實線))

我使用以下代碼:

library("ggplot2") 
pd <- position_dodge(0.1) #The errorbars overlapped, so use position_dodge to move 
          #them horizontally 
plot<-ggplot(a, aes(x=group, y=mean, colour=as.factor(factor), linetype=model)) + 
    geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.1, position=pd) + 
    geom_point(position=pd, size=3, shape=21, fill="white") + # 21 is filled circle 
    xlab("Groups") + 
    ylab("Power") + 
    geom_line(position=pd) + 
    scale_linetype_manual(values = c(new = "solid", old = "dashed")) 

enter image description here

但「平均值±sd」應該都是實線,並且應該被添加點之間連接。其實我想它是這樣的:

enter image description here 你能給我一些建議,謝謝!

回答

3

我建議增加一個新的分組變量:

a$group2 <- paste(a$factor, a$model, sep="_") 

然後從ggplot()刪除linetype和修改geom_line()

ggplot(a, aes(x = group, y = mean, colour = as.factor(factor))) + 
     geom_errorbar(aes(ymin = mean-sd, ymax = mean+sd), 
        width = .1, position = pd) + 
     geom_point(position = pd, size = 3, shape = 21, fill = "white") + 
     xlab("Groups") + 
     ylab("Power") + 
     geom_line(aes(x = group, y = mean, colour = as.factor(factor), 
        group = group2, linetype = model)) + 
     scale_linetype_manual(values = c(new = "solid", old = "dashed")) 

enter image description here

+1

太謝謝你了!看起來很好!但是有一個問題:同一種顏色的新模型和舊模型是重疊的,你可以幫助處理這個問題,謝謝! @beetroot – lightsnail

+0

例如,在B組中,兩個紅色的「mean±sd」重疊,最好不要將它們排列在同一個x軸上,更小的間隙會更好。 – lightsnail

+0

如果我設置「pd < - position_dodge(1)」,那麼使用你的代碼的格雷就會變得有點奇怪。 @beetroot – lightsnail