【问题标题】:Format date-time axis in real time histogram in R?在R中的实时直方图中格式化日期时间轴?
【发布时间】:2018-10-02 17:16:21
【问题描述】:

我正在尝试在实时直方图中修复未格式化的日期时间轴。我正在使用类似的示例改编自 Time/Date real time plot in R.

n <- 5000
df <- data.frame(time = Sys.time()+1:n, y = runif(n))
window <- 1000

for(i in 1:(n-window)) {
    flush.console()
    df1 <- df[i:(i+window), ]
    h <- hist(as.POSIXct(df1$time), breaks = "mins",  yaxt = "n", 
              col = "gray", main = NULL, freq = TRUE, xlab = "", 
              plot = FALSE, format = "%d %H:%M")
    plot(h, breaks = "mins", col = "gray", main = NULL, freq = TRUE, 
         xlab= "", format = "%d %H:%M")
    Sys.sleep(0.01)
}

另外,我用下面的代码尝试了一半成功。但可悲的是,x 轴显示日期时间就像一个闪光,如果我减少更多Sys.sleep,日期时间轴就会消失,在我的第一个示例中,轴看起来不像未格式化的日期时间轴那么好。

n <- 5000
df <- data.frame(time = Sys.time()+1:n, y = runif(n))
window <- 1000

for(i in 1:(n-window)) {
    flush.console()
    df1 <- df[i:(i+window), ]
    x_at <- pretty(df1$time)
    x_labels <- format(pretty(df1$time), "%d %H:%M")
    hist(df1$time, df1$y,type='l', breaks = "mins", xaxt = 'n')
    axis.POSIXct(side = 1, at = x_at, labels = x_labels)
    Sys.sleep(0.01)
}

能否以更好的方式查看 x 轴?

【问题讨论】:

    标签: r date plot time axis-labels


    【解决方案1】:

    问题是hist() 在您传递一个 POSIXt 对象时知道时间轴,但是当您传递一个直方图对象时 plot() 不知道h。因此,只需一步完成所有操作,而不是两步:

     n=5000
     df=data.frame(time=Sys.time()+1:n,y=runif(n))
     window=1000
     for(i in 1:(n-window))
     {
        flush.console()
        df1 <-df[i:(i+window),]
        hist(as.POSIXct(df1$time), breaks="mins",  
          yaxt = "n", col="gray", main=NULL, freq = TRUE, xlab= "", 
          format = "%d %H:%M")
        Sys.sleep(0.01)
     }
    

    【讨论】:

    • 是的,我知道。在我的第二个示例中,我得到了相同的结果。此外,我确实评论说轴日期时间随着 Sys.sleep 低于(0.1)而消失,因此我提出了这个问题。谢谢
    猜你喜欢
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 2016-12-13
    相关资源
    最近更新 更多