hjw hjw - 3 months ago 20
R Question

Scatter plot with ggplot2 colored by dates

I am trying to do a scatter plot with colored by dates. Currently I am doing the following but I have not been able to find a way to get the dates in a good readable format for the legend even though the graph looks the way I want it. I tried formatting them as 20140101 for example but the whole year falls within a small range i.e < 20141231 and I don't get different colors within the year.

data(cars)
cars['dt'] = seq(Sys.Date(),Sys.Date()-980,-20)

ggplot(cars,aes(speed,dist,colour = as.integer(dt))) + geom_point(alpha = 0.6) +
scale_colour_gradientn(colours=c('red','green','blue'))


Can someone recommend a solution please? To be specific I would like every date to be a different color/shade of a color. (For my actual data I have about 5-6 years of daily data)

enter image description here

Answer

Just add a labeler function:

ggplot(cars,aes(speed,dist,colour=as.integer(dt))) + geom_point(alpha = 0.6) +
  scale_colour_gradientn(colours=c('red','green','blue'), labels=as.Date)

enter image description here