Fatalize
Fatalize

Reputation: 3543

Plotting a time series where color depends on a category with ggplot

Consider this minimum working example:

library(ggplot2) 
x <- c(1,2,3,4,5,6)
y <- c(3,2,5,1,3,1)
data <- data.frame(x,y)
pClass <- c(0,1,1,2,2,0)

plottedGraph <- ggplot(data, aes(x = x, y = y, colour = factor(pClass))) + geom_line()
print(plottedGraph)

I have a time series y = f(x) where x is a timestep. Each timestep should have a color which depends on the category of the timestep, recorded in pClass.

This is the result it gives:

enter image description here

It doesn't make any kind of sense to me why ggplot would connect points with the same color together and not points that follow each other (which is what geom_line should do according to the documentation).

How do I make it plot the following:

enter image description here

Upvotes: 2

Views: 814

Answers (1)

mtoto
mtoto

Reputation: 24188

You should use group = 1 inside the aes() to tell ggplot that the different colours in fact belong to the same line (ie. group).

ggplot(data, aes(x = x, y = y, colour = factor(pClass), group = 1)) + 
  geom_line()

enter image description here

Upvotes: 6

Related Questions