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)
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With