Robert
Robert

Reputation: 1028

Create coloured lines

For several subjects I am trying to plot a coloured timeline where each color represents a state. I created some random data to show you what I mean.

require(dplyr)
require(ggplot2)
df=data_frame(subject=factor(rep(1:4,each=100)),
              time=rep(1:100,4),
              state=sample(letters[1:4],400,replace=TRUE)) %>%
   group_by(subject) %>% 
   mutate(time=time+round(runif(1,min=0,max=20)))

ggplot(df,aes(x=subject,y=time,color=state,group=1)) +
   geom_line(size=10)+coord_flip()

the image I have so far

The problem is the lines from one subject to another. I tried adding not-a-number values or NULLs at the end of each line but that didn't work. Does anyone know a way to remove the diagonal lines? (Alternative ways to produce the same kind of plot are welcome to.)

Upvotes: 1

Views: 34

Answers (1)

tonytonov
tonytonov

Reputation: 25608

group aesthetic is responsible for that. Adding group = subject will help:

ggplot(df,aes(x=subject,y=time,color=state,group=subject)) +
    geom_line(size=10)+coord_flip()

enter image description here

Upvotes: 1

Related Questions