Reputation: 199
I want to plot the a single line representing aggregate density by sex on this graph. In other words, I want to plot another layer that is the average of all the lines, grouped by sex. I tried my best to create a reproducible example, and came pretty close:
library(ggplot2)
A <- c(rnorm(2000, mean = 20, sd = 2), rnorm(2000, mean = 30, sd = 3))
B <- rep(c(1:100), 40)
C <- as.factor(c(rep(1, 2000), rep(2,2000)))
data <- data.frame("CT" = A, "ID" = B, "Sex" = C)
ggplot(data, aes(x=CT)) +
geom_line(aes(color=Sex, group = interaction(ID, Sex)), stat="density", size=0.3, alpha=0.4)
Upvotes: 0
Views: 201
Reputation: 3532
You can just add another geom_line()
without the grouping variable, which will give what I think you're looking for:
ggplot(data, aes(x=CT)) +
geom_line(aes(color=Sex, group = interaction(ID, Sex)), stat="density", size=0.3, alpha=0.4) +
geom_line(stat="density")
which gives:
Or, if you still want average density of the lines within each Sex grouping, you can replace the last line above with:
geom_line(stat="density", aes(group=Sex), size=1.25)
or
geom_line(stat="density", aes(colour=Sex), size=1.25)
if you want the colours to match.
Upvotes: 1