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()
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))
How do I either (1) specify a custom color scale in the first plot, or (2) maintain POSIXct legend entries in the 2nd plot?
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:
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