Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scatter plot with ggplot2 colored by dates

Tags:

r

ggplot2

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

like image 533
hjw Avatar asked Jan 23 '14 14:01

hjw


2 Answers

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

like image 151
BrodieG Avatar answered Nov 09 '22 05:11

BrodieG


Getting around the 'origin must be supplied error'... One approach is to make a wrapper for as.Date that has the origin specified, than call this as a labeller.

as.Date_origin <- function(x){
  as.Date(x, origin = '1970-01-01')
}

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(name = 'Date', colours=c('red','green','blue'), labels=as.Date_origin)
like image 28
Tony Ladson Avatar answered Nov 09 '22 05:11

Tony Ladson