【问题标题】:Using scale_color with a variable of class date produces Error: as.Date.numeric(value) : 'origin' must be supplied将 scale_color 与类日期变量一起使用会产生错误:as.Date.numeric(value) : 'origin' must be provided
【发布时间】:2019-07-09 00:45:38
【问题描述】:

我正在尝试使用 ggplot2 按日期着色,但是当我尝试使用 scale_color_gradient2 自定义颜色时,我收到错误消息 Error in as.Date.numeric(value) : 'origin' must be supplied

我似乎无法弄清楚如何将来源传递给scale_color_gradient2

我在下面提供了一个示例。有什么建议吗?

set.seed(1)
x1 <- rnorm(100)
x2 <- rnorm(100)
day <- sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 100)

myData <- data.frame(x1, x2, day)

# this plot works as expected
ggplot(myData, aes(x = x1, y = x2, color = day)) + geom_point()

# scale_color_gradient2() asks for an origin, but I can't figure out how to supply one
ggplot(myData, aes(x = x1, y = x2, color = day)) + geom_point() +
    scale_color_gradient2()

【问题讨论】:

    标签: r date ggplot2 colors tidyverse


    【解决方案1】:

    scale_color_gradient2 需要添加两件事:trans = "date"* 和合理的midpoint(默认为 0)。我用mean'day'。请注意,您需要scale 中均值的数字版本:

    ggplot(myData, aes(x = x1, y = x2, color = day)) +
      geom_point() +
      scale_color_gradient2(trans = "date", midpoint = as.numeric(mean(myData$day)))
    


    您可能想要更改图例中的默认中断和标签。首先,创建一个中断序列,使用seqpretty

    brk <- seq.Date(min(myData$day), max(myData$day), by = "3 month")
    # brk <- pretty(myData$day)
    

    breakslabels 设置为您想要的format

    scale_color_gradient2(trans = "date", midpoint = as.numeric(mean(myData$day)), 
                          breaks = brk,
                          labels = format(brk, "%Y-%m")) 
    

    编辑以下评论:

    scale_color_gradient2POSIXct 变量一起使用

    trans = "time" 和一个明智的midpoint 添加到scale_color_gradient2。在这里,我使用平均“时间”。请注意,您需要 scale 中平均值的数字版本。

    # some data
    d <- data.frame(x = 1:10, y = 1, time = as.POSIXct("2019-02-15 12:00") + 1:10)
    
    ggplot(d, aes(x = x, y = y, color = time)) +
      geom_point() +
      scale_color_gradient2(trans = "time", midpoint = as.numeric(mean(d$time)))
    


    可能更改图例中的中断和标签,例如

    brk <- pretty(d$time)
    
    ggplot(d, aes(x = x, y = y, color = time)) +
      geom_point() +
      scale_color_gradient2(trans = "time", midpoint = as.numeric(mean(d$time)),
                            breaks = brk, labels = format(brk, format = "%H:%M:%S"))
    

    *在当前版本的ggplot2 (3.1.0) 中,从文档中看不出trans = "date"trans = "time" 的存在。它们既没有在?scale_color_gradient 等人的trans 参数中提及,也没有在?continuous_scale 中提及。但是,我提交了一个问题,因此文档有望在下一个版本中更新。

    【讨论】:

    • 谢谢!这对我有用。作为后续,有没有办法在 scale_color_gradient 中使用 POSIXct 类而不将其转换为 Date 类?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多