将自定义颜色渐变映射到 POSIXct 值

Map custom color gradient to POSIXct values

数据:

df1 <- structure(list(Index = 1:11, Duration = structure(c(1487577655, 
1487577670, 1487577675, 1487577680, 1487577685, 1487577680, 1487577700, 
1487577705, 1487577695, 1487577700, 1487577680), class = c("POSIXct", 
"POSIXt"), tzone = "")), .Names = c("Index", "Duration"), class = "data.frame", row.names = 3:13)

现在我构造图如下:

g1 <- ggplot(df1, aes(x = Index, y = Duration, color = Duration))+
geom_point()+
geom_line()+
scale_y_datetime(labels = date_format("%M:%S"))

现在,色阶设置为默认的 "Black" 到 "Blue" 渐变。

问题是,我在尝试为数据分配自定义梯度时遇到错误。

对于非 POSIXct 对象:

scale_color_gradient("Duration", low = "#D80427", high = "#07a0ff", space = "Lab")

有效,但我收到以下错误,将 POSIXct 对象 df1$Duration 作为解释变量:

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

绘制 POSIXct 对象时是否需要使用不同的梯度函数?

我们可以将日期转换为颜色的数字:

library(ggplot2)
library(scales)

ggplot(df1, aes(x = Index, y = Duration, color = as.numeric(Duration))) +
  geom_point() +
  geom_line() +
  scale_y_datetime(labels = date_format("%M:%S")) +
  scale_color_gradient("Duration", low = "#D80427", high = "#07A0FF",
                       labels = c("00", "10", "20", "30", "40"))

根据 @Henrik 的建议,为避免对标签进行硬编码,请使用以下内容:

# avoid hardcoding labels using pretty()
ggplot(df1, aes(x = Index, y = Duration, color = as.numeric(Duration))) +
  geom_point() +
  geom_line() +
  scale_y_datetime(labels = date_format("%M:%S")) +
  scale_color_gradient("Duration", low = "#D80427", high = "#07A0FF",
                       breaks = pretty(as.numeric(df1$Duration)),
                       labels = format(pretty(df1$Duration), "%M:%S"))

您可以使用 trans = time_trans():

library(ggplot2)
library(scales)
g1 +
  scale_color_gradient("Duration", low = "#D80427", high = "#07a0ff",
                       trans = time_trans())

如果您希望在图例中添加另一个 format 标签,请添加例如labels = format(pretty(df1$Duration), "%M:%S").