2017-04-10 23 views
0

我有小數據框架,我想要創建一個條形圖,其中的線條顯示羣組之間的平均水平。在ggplot2中跨越多個小組的線條

數據框:

cpcost = c("Coll.Punishment","Coll.Punishment", "Ind.Punishment", 
      "Ind.Punishment") 
color = c(0,1,0,1) 
mysum = c(0.3408240, 0.2935982, 0.3460490, 0.1267057) 
genlevel = c(0.3111111,0.3111111, 0.2181818, 0.2181818) 
temp = as.data.frame(cbind(cpcost,color,mysum,genlevel)) 

所以結果看起來是這樣的:

enter image description here

的問題是,現在我在一個非常醜陋的方式在做(見下文)。 我基本上首先添加水平誤差線。但後來因爲對於每個條錯誤條之間的小空間:

enter image description here

我也畫一條水平線,以填補誤差線之間這狹小的空間。 (如果我繪製唯一的水平條,它將從條的中間開始)。

enter image description here

我相信有更優雅的方式來達到同樣的效果。 我該怎麼做?

謝謝!

ggplot(temp, aes(group=cpcost), 
      y = genlevel) + 
     geom_bar(stat = "identity",aes(x = factor(color), 
            y = mysum, 
            group=cpcost, 
            fill = factor(color))) + 
     geom_errorbar(aes(x=factor(color), 
          y=genlevel, 
          ymin=genlevel, 
          ymax=genlevel, 
         group=cpcost 
         )) + 
     geom_line(aes(x=factor(color), y=genlevel,group=cpcost)) + 
     labs(x = "Round", y = "Share of Emptying") + 
     scale_fill_discrete(name='Crime',               
labels=c("No", "Yes")) + 
     ggtitle('Whistleblowing')+ 
     facet_grid(~cpcost) 

回答

1

這會給你一個稍微不同的結果,但我希望這是你需要足夠的好。它的清潔,並使用內置geom_hline

library(ggplot2) 

df <- data.frame(cpcost = c("Coll.Punishment", "Coll.Punishment", "Ind.Punishment", "Ind.Punishment"), 
       color = c(0,1,0,1), 
       mysum = c(0.3408240, 0.2935982, 0.3460490, 0.1267057), 
       genlevel = c(0.3111111,0.3111111, 0.2181818, 0.2181818)) 

ggplot(df) + 
    geom_col(aes(factor(color), mysum, fill = factor(color))) + 
    geom_hline(aes(yintercept = genlevel)) + 
    scale_fill_discrete(name='Crime', labels=c("No", "Yes")) +   
    facet_wrap(~ cpcost) + 
    labs(x = "Round", y = "Share of Emptying") + 
    ggtitle('Whistleblowing') 

+0

完美!非常感謝! –