1

I want to plot (with ggplot) multiple sets of lines where the sets of lines are nested within groups, i.e. group 1 consists of two separate lines, group 2 consists of two separate lines etc but those lines should have the same color across groups. I know that I could use a loop to go through the groups but I'd like to avoid that. The result should look similar to this (ignore the bold line).

Example

This code produces an example dataset.

y <- rep(NA, 60)
y[1] <- rnorm(1, 0, 0.5)
for (t in 2:60){
  y[t] <- rnorm(1, y[t - 1], 0.5)
}
n <- 2

data <- as.data.frame(cbind(rbind(cbind(rep(seq(1, 30), n), sort(rep(seq(1, n), 30)), y), cbind(rep(seq(1, 30), n), sort(rep(seq(1, n), 30)), y),cbind(rep(seq(1, 30), n), sort(rep(seq(1, n), 30)), y)), sort(rep(seq(1, 3), 30)))         )
colnames(data) <- c("t", "n", "y", "group")
data$y <- data$y + rnorm(3 * 30 * 2, 0, 0.1)

1 Answer 1

2

I think the answer to your question was addressed in this post: Using geom_line with multiple groupings

So you can use interaction in ggplot, based on your data, the code looks like:

library(ggplot2)
g = ggplot(data,aes(x = t, y = y,group = interaction(as.factor(n),as.factor(group)),color = as.factor(group)))
g + geom_line() 

You should get the graph you are looking for. enter image description here

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

1 Comment

That's exactly what I was looking for. Thank you! I didn't see the previous post. I didn't think it came up when I scrolled through the suggestion.s

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.