Just trying to understand how geom_abline works with faces in ggplot.
I have a student test data set. They are in a dt data table with 4 columns:
student: unique student ID
cohort: grouping factor for students (A, B, … H)
subject: subject of the test (English, Math, Science)
score: the test score for that student in that subject
The goal is to compare cohorts. The following snippet creates a sample dataset.
library(data.table)
cohorts <- data.table(name=toupper(letters[1:8]),size=as.numeric(c(8,25,16,30,10,27,13,32)))
base <- data.table(student=c(1:sum(cohorts$size)),cohort=rep(cohorts$name,cohorts$size))
english <- data.table(base,subject="English", score=rnorm(nrow(base), mean=45, sd=50))
math <- data.table(base,subject="Math", score=rnorm(nrow(base), mean=55, sd=25))
science <- data.table(base,subject="Science", score=rnorm(nrow(base), mean=70, sd=25))
dt <- rbind(english,math,science)
dt$score<- (dt$score>=0) * dt$score
dt$score<- (dt$score<=100)*dt$score + (dt$score>100)*100
The following displays indicate a cohort score with 95% CL, a faceted subject, and an inclusive (blue, dotted) reference line (using geom_abline).
library(ggplot2)
library(Hmisc)
ggp <- ggplot(dt,aes(x=cohort, y=score)) + ylim(0,100)
ggp <- ggp + stat_summary(fun.data="mean_cl_normal")
ggp <- ggp + geom_abline(aes(slope=0,intercept=mean(score)),color="blue",linetype="dashed")
ggp <- ggp + facet_grid(subject~.)
ggp
The problem is that the reference line (from geom_abline) is the same in all faces (= average GPA for all students and all subjects). Therefore, stat_summary seems to respect the grouping implied in facet_grid (for example, by topic), but abline does not. Can anyone explain why?
NB: , , geom_abline (), ?
means <- dt[,list(mean.score=mean(score)),by="subject"]
ggp <- ggplot(dt,aes(x=cohort, y=score)) + ylim(0,100)
ggp <- ggp + stat_summary(fun.data="mean_cl_normal")
ggp <- ggp + geom_abline(data=means, aes(slope=0,intercept=mean.score),color="blue",linetype="dashed")
ggp <- ggp + facet_grid(subject~.)
ggp