0
votes

I have the small data frame and I would like to build a bar chart with lines that show average levels across groups.

dataframe:

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))

So the result looks like this:

enter image description here

The problem is that now I am doing in in a really UGLY way (see below). I basically add horizontal error bars first. but then since there is a small space between errors bars for each bar:

enter image description here

I also draw a horizontal line to fill this small space between error bars. (If I draw the only horizontal bar it will start from the middle of bar).

enter image description here

I do believe that there is much more elegant way to reach the same result. How should I do it?

Thanks!

    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

1 Answers

1
votes

This will give you a slightly different result, but I hope it's good enough for your need. It's cleaner and use the built-in 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')