With some help from this group and Stackoverflow, I was able to add vertical lines marking the means in a grouped density plot. However, the vertical lines extend all the way from the very bottom to the very top of the plot region. Is there any way to clip the lines so that they stay inside the borders of the density plot?
Here's a reproducible example with fake data:
df =structure(list(group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L), .Label = c("Group 1", "Group 2"), class = "factor"), score = c(10.8,
11.7, 15.2, 5.8, 11.7, 8.4, 7.7, 12.7, 11.5, 8.9, 9.6, 7.2, 10,
9.8, 7.3, 7.9, 7.4, 10.3, 13, 11.5, 13.1, 7.9, 14.5, 4.1, 4,
7.6, 0.1, 4.5, 6.5, -1.3, 2.2, 5.1, 6.2, 3.1, 8.3, 5, 4, 4.1,
-0.2, 12.4)), .Names = c("group", "score"), row.names = c(NA,
-40L), class = "data.frame")
grp.mean = ddply(df, .(group), summarise, mean=mean(score))
ggplot(df, aes(score, fill=group)) +
geom_density(lwd=.7,alpha=.4) +
geom_vline(data=grp.mean,
mapping=aes(xintercept=mean, colour=group), lwd=1)
I'd like to clip the vertical lines so that they remain inside the borders of the density curves.
Thanks for any suggestions on how to do this.
Joel