Monody
Monody

Reputation: 45

Plotting multiple sets of lines with sets nested in groups

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)

Upvotes: 1

Views: 1169

Answers (1)

dc37
dc37

Reputation: 16178

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

Upvotes: 2

Related Questions