Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 legend entries change from posixct to integer when using scale_color_gradientn

I'd like to make a path plot in ggplot2, with the path based on a timeseries, and a continuous color aesthetic to show this path. The legend should associate the color with timeseries. The legend is nice when the color aesthetic is defined in the original call to ggplot:

library(tidyverse)

times <- seq.POSIXt(from = as.POSIXct("2017-10-01 02:00:00"),
                    to = as.POSIXct("2017-10-03 12:34:00"), 
                    by = "min")
values <- rnorm(length(times))

dat <- data.frame(times = times, 
                  values1 = sin(values[order(values)]), 
                  values2 = cos(values[order(-values)]))

ggplot(dat, aes(values1, values2, color=times)) +
  geom_path()

Legend is good!

However, I want to use a different color scale than the default. When using scale_color_gradientn, or scale_color_continuous, the legend entries seem to get converted from POSIXct to integers:

ggplot(dat, aes(x = values1, y = values2, color = times)) +
  geom_path() +
  scale_color_gradientn(colors = rainbow(4))

Legend not so good!!

How do I either (1) specify a custom color scale in the first plot, or (2) maintain POSIXct legend entries in the 2nd plot?

like image 272
Eric Krantz Avatar asked Oct 15 '25 16:10

Eric Krantz


1 Answers

Looking at scale_colour_datetime() which is used by default, all it does is:

scale_colour_continuous(trans = "time")

So adding trans = "time" to your desired colour scale works:

ggplot(dat, aes(values1, values2, color=times)) +
    geom_path() +
    scale_color_gradientn(colors = rainbow(4), trans = "time")

Output:

enter image description here

like image 164
Marius Avatar answered Oct 17 '25 05:10

Marius