【问题标题】:Changing a continuous color scale with POSIXt objects使用 POSIXt 对象更改连续色标
【发布时间】:2019-05-16 02:54:11
【问题描述】:

假设我们在二维空间中有一系列随时间变化的位置:

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()

这给出了以下图表:

现在我想将调色板更改为更“动态”的颜色,比如颜色酿造器的 Spectral 调色板。

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

但我有一个错误:

Ops.POSIXt((x - from[1]), diff(from)) 中的错误: '/' 没有为“POSIXt”对象定义

(我得到的实际错误的粗略翻译,一半是英语/一半是法语)。

我猜想在某些时候,scale_color_gradientn 会尝试将我的时间刻度分成相等的部分,但没有这样做,因为它不知道如何划分日期。

那我该怎么办?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    你可以用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")
    

    scale_color_brewer 仅适用于离散日期

    【讨论】:

      猜你喜欢
      • 2013-03-08
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多