【问题标题】:how to plot timeDate using ggplot2 in R?如何在 R 中使用 ggplot2 绘制 timeDate?
【发布时间】:2016-11-17 19:40:29
【问题描述】:
library(timeDate)
library(ggplot2)
library(ggrepel)

dataset1$TimeStamp <- timeDate(dataset1$TimeStamp, format = "%Y/%m/%d   %H:%M:%S", zone = "GMT", FinCenter = "GMT")

p1 <- ggplot(dataset1, aes(x = TimeStamp, y = y1))

p1 + 
geom_point() + 
geom_text_repel(aes(label = Label1), size = 3)

注意: 当执行上面的代码时,我会看到下一个: 不知道如何为 timeDate 类型的对象自动选择比例。默认为连续。 错误:geom_point 需要以下缺失的美学:x

如何在ggplot中使用timeDate类?

【问题讨论】:

    标签: r date time ggplot2


    【解决方案1】:

    可能 ggplot 不知道如何处理 timeDate 类。您可以简单地将TimeStamp@Data 插槽中的值插入ggplot:

    dataset1 <- data.frame(TimeStamp = sample(1:100,50,replace = T), 
                           y1=sample(1:50,50,replace=T),
                           Label1 = sample(LETTERS[1:5],50,replace=T)
                           )
    dataset1$TimeStamp <- timeDate(dataset1$TimeStamp, 
                                   format = "%Y/%m/%d %H:%M:%S", 
                                   zone = "GMT", 
                                   FinCenter = "GMT"
                                   )
    str(dataset1$TimeStamp)
    
    # Formal class 'timeDate' [package "timeDate"] with 3 slots
    # ..@ Data     : POSIXct[1:100], format: "1970-01-01 00:00:09" "1970-01-01 00:00:05" "1970-01-01 00:00:06" ...
    # ..@ format   : chr "%Y-%m-%d %H:%M:%S"
    # ..@ FinCenter: chr "GMT"
    
    str(dataset1$TimeStamp@Data)
    
    # Dates in POSIXct format are storred in @Data slot
    # POSIXct[1:100], format: "1970-01-01 00:00:09" "1970-01-01 00:00:05" "1970-01-01 00:00:06" "1970-01-01 00:00:04" ...
    
    ggplot(dataset1, aes(x = TimeStamp@Data, y = y1, colour = Label1)) +
      geom_point() + 
      geom_text_repel(aes(label = Label1, colour = Label1), size = 3) +
      theme_dark() +
      labs(x="Time Stamp", y = "Value") +
      scale_colour_discrete(guide = F)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-13
      • 2021-02-10
      • 2017-06-19
      • 2023-03-22
      • 2013-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多