2

Suppose I have some code like the following, generating a lineplot with a considerable number of lines (example taken from here)

library(ggplot2)
library(reshape2)

n = 1000
set.seed(123)

mat = matrix(rnorm(n^2), ncol=n)
cmat = apply(mat, 2, cumsum)
cmat = t(cmat)
rownames(cmat) = paste("trial", seq(n), sep="")
colnames(cmat) = paste("time", seq(n), sep="")

dat = as.data.frame(cmat)
dat$trial = rownames(dat)
mdat = melt(dat, id.vars="trial")
mdat$time = as.numeric(gsub("time", "", mdat$variable))


p = ggplot(mdat, aes(x=time, y=value, group=trial)) +
    theme_bw() +
    theme(panel.grid=element_blank()) +
    geom_line(size=0.2, alpha=0.1)

enter image description here

So here, "trial number" is my group producing all of these lines, and there are 1000 trials. Suppose I want to "group my grouping variable" now - that is, I want to see the exact same lines in this plot, but I want the first 500 trial lines to be one color and the next 500 trial lines to be another. How can I do this with ggplot? I've been poking around for some time and I can't figure out how to manually set the colors per group.

Eric Hansen
  • 1,749
  • 2
  • 19
  • 39

2 Answers2

3

Add a variable splitting the data into two groups, then add use it to color the lines in ggplot

dat = as.data.frame(cmat)
dat$trial = rownames(dat)
dat$group = rep(c("a","b"), each = n/2)
mdat = melt(dat, id.vars=c("trial", "group"))
mdat$time = as.numeric(gsub("time", "", mdat$variable))


p = ggplot(mdat, aes(x=time, y=value, group=trial, color = group)) +
  theme_bw() +
  theme(panel.grid=element_blank()) +
  geom_line(size=0.2, alpha=0.1)
GordonShumway
  • 1,980
  • 13
  • 19
2

One possible solution will be to create a new column with the index of the trial number and then using an ifelse condition, you can set different group based on the trial number and pass the grouping variable as color in aes such as:

mdat %>% mutate(Trial = as.numeric(sub("trial","",trial))) %>%
  mutate(Group = ifelse(Trial < 51,"A","B")) %>%
  ggplot(aes(x=time, y=value, group=trial, color = Group)) +
  theme_bw() +
  theme(panel.grid=element_blank()) +
  geom_line(size=0.2, alpha=0.8)

enter image description here

Is it what you are looking for ?


NB: I only use n = 100 to get smallest dataframe.

dc37
  • 15,840
  • 4
  • 15
  • 32