I have two datsets in my diagram, "y1" and "baseline". As labels in a ggplot diagram, I want to use the difference of the y-value of both. I want to facilitate this on the fly.
Dataframe:
df <- data.frame(c(10,20,40),c(0.1,0.2,0.3),c(0.05,0.1,0.2))
names(df)[1] <- "classes"
names(df)[2] <- "y1"
names(df)[3] <- "baseline"
df$classes <- factor(df$classes,levels=c(10,20,40), labels=c("10m","20m","40m"))
dfm=melt(df)
To start with, I defined a function which returns the y-value of the baseline corresponding to a particular x-value:
Tested it, works fine:
getBaselineY <- function(xValue){
return(dfm[dfm$classes==xValue & dfm$variable=="baseline",]$value[1])
}
Unfortunately, parsing this function into the ggplot code only gives me the baseline y-value for the first x-value:
diagram <- ggplot(dfm, aes(x=classes, y=value, group=variable, colour=variable))
diagram <- diagram + geom_point() + geom_line()
diagram <- diagram + geom_text(aes(label=getBaselineY(classes)))
diagram <- diagram + theme_bw(base_size=16)
diagram
Nevertheless, subsetting the function call by just the x-value gives me the respective x-value for each ggplot-iteration:
diagram <- diagram + geom_text(aes(label=classes))
I don't understand how this come and how to solve it the best way. Any help is highly appreciated!
Alternatively, this could be solved by calculating the difference beforehand and adding an additional column to the data frame:
df$Difference<-df$y1-df$baseline
dfm=melt(df,id.var=c(1,4))
And use it directly as geom_text label:
diagram <- diagram + geom_text(aes(label=Difference))