2017-04-10 3 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

問題が(下記参照)、今私は本当にUGLY方法ででやっているということです。 私は基本的に横のエラーバーを最初に追加します。しかし、その後、各バーについてのエラーバーの間に小さなスペースがあるので:

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

完璧!どうもありがとう! –

関連する問題