Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join with a line the results from stat_summary()

Tags:

r

ggplot2

I'm trying to make a ggplot graph wich show the proportions of a variable (SIZE) according to another one (ZONE) using face_grid, then in every category show the mean of a binary variable (BG) using stat_summary. But now, I want to join the points (the means) and show the mean in percent format (near the point). For join the points I've tried with stat_summary('arguments here',geom="line") and other commands but the truth is I don't know how to do it.

    library(ggplot2)
    library(scales)

    set.seed(100)

    data <- data.frame(ID = 1:600,
                   SIZE = rep(c('B','M','S'), each = 200), 
                   ZONE = sample(c('A','B'), size = 600, replace=T),
                   BG = c(sample(0:1, size = 200, prob = c(1,1), replace=T),
                          sample(0:1, size = 200, prob = c(2,3), replace=T),
                          sample(0:1, size = 200, prob = c(1,2), replace=T)))

    ggplot(data, aes(x = SIZE)) + 
      geom_bar(aes(y = (..count..)/sum(..count..))) +
      facet_grid(~ZONE) + 
      stat_summary(aes(y = BG), fun.y=mean, colour="red", geom="point", size = 3) + 
      scale_y_continuous('Percent', labels = percent_format())

Thanks in advance and sorry for my english.

like image 290
jbkunst Avatar asked Oct 08 '22 09:10

jbkunst


1 Answers

Always remember the group aesthetic when using geom_line!

ggplot(data, aes(x = SIZE)) + 
      geom_bar(aes(y = (..count..)/sum(..count..))) +
      facet_grid(~ZONE) + 
      stat_summary(aes(y = BG,group = 1), fun.y=mean, colour="red", geom="line", size = 3) + 
      scale_y_continuous('Percent', labels = percent_format())
like image 67
joran Avatar answered Oct 13 '22 01:10

joran