2016-12-16 33 views
0

假設我們有一個系列在2D空間中的位置的隨時間變化:改變與POSIXt連續色標對象

start.time <- strptime("2016-11-22_15-44-24", 
         format = "%Y-%m-%d_%H-%M-%S", 
         tz = "UTC") 

end.time <- strptime("2016-11-22_17-25-12", 
        format = "%Y-%m-%d_%H-%M-%S", 
        tz = "UTC") 
date <- seq.POSIXt(from = start.time, to = end.time, length.out = 100) 
a <- seq(0, 10, length.out = 100) 
x <- a * cos(a) 
y <- a * sin(a) 
my.df <- data.frame(date, x, y) 

ggplot(my.df, aes(x, y, color = date)) + geom_point() 

這給了下面的圖:

enter image description here

現在我想將顏色調色板更改爲更「動態」的顏色調色板,例如顏色調製器的調色板。

this answer,我用命令:

myPalette <- colorRampPalette(rev(brewer.pal(11, "Spectral"))) 
sc <- scale_colour_gradientn(colours = myPalette(100)) 

ggplot(my.df, aes(x, y, color = date)) + geom_point() + sc 

但我有一個錯誤:

Error in Ops.POSIXt((x - from[1]), diff(from)) : '/' not defined for "POSIXt" objects

(從實際的錯誤,我得到的,這是一半英語/半法文粗略的翻譯) 。

我想在某些時候,scale_color_gradientn試圖將我的時間尺度分成相等的部分,但不能這樣做,因爲它不知道如何劃分日期。

那我該怎麼辦?

回答

2

,你可以做一個小數字變通這樣與scale_color_distiller

library(lubridate) 
ggplot(my.df, aes(x, y, color = as.numeric(date))) + 
    geom_point() + 
    scale_color_distiller(palette = "Spectral", 
          breaks = as.numeric(my.df$date[c(1,50,100)]), 
          labels = paste0(hour(my.df$date[c(1,50,100)]), ":", minute(my.df$date[c(1,50,100)])), 
          name = "date") 

enter image description here

scale_color_brewer將只用於離散日期

工作