0

enter image description here

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)

1 Answer 1

1

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:

enter image description here

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.