5

With the following code:

myPlot <- ggplot(data=df, aes(x=xVal, y=yVal, color=as.integer(Date) ) ) +
    geom_point() +
    scale_colour_gradient(low="blue", high="red" ) +
    labs(color="Date")

I am able to get a simple gradient of colour by date. However, the legend displays these as integers which is not helpful. How can I convert these integers back to date for display on the legend?

I want to keep the automatic limits, so that I can use this as a part of a function for data of any date range.

Daniel Hoare
  • 254
  • 2
  • 10

1 Answers1

3

With the help of this answer I have been able to find a solution.

myPlot <- ggplot(data=df, aes(x=xVal, y=yVal, color=as.integer(Date) ) ) +
    geom_point() +
    scale_colour_gradient(low="blue", high="red" breaks=myBreaks) +
    labs(color="Date")

myBreaks <- function(x){
    breaks <- c(min(x),median(x),max(x))
    attr(breaks,"labels") <- as.Date(breaks, origin="1970-01-01")
    names(breaks) <- attr(breaks,"labels")
    return(breaks)
}
Community
  • 1
  • 1
Daniel Hoare
  • 254
  • 2
  • 10