在R中使用时间轴(日期戳)操作绘图



下面的R代码创建了一个带有两个控制x轴范围的交互式滑块的图形:

library(manipulate)
x = 1:100
y = 1:100*2
manipulate(plot(x, y, xlim=c(x.min,x.max)),
           x.min = slider(min(x),max(x)),
           x.max = slider(min(x),max(x)) )

现在我想做同样的事情,但x值是一个时间序列。例如:

# Create a date vector length 100 in day increments from the date "2014-01-01"
x = seq(from=as.POSIXct("2014-01-01"), by=as.difftime(1, units="days"), length.out=100)
y = 1:100*2
manipulate(plot(x, y, xlim=c(x.min,x.max)),
               x.min = slider(min(x),max(x)),
               x.max = slider(min(x),max(x)) )

但是,我得到一个错误:

滑块(min(x), max(x))错误:最小、最大和初始值必须都是数值

我认为这是因为min(x)不是数字,它是一个日期。但是我该如何处理日期呢?

我已经根据以下SO链接配置了您的问题:如何操纵(使用操纵pkg)带时间戳轴的ggplot2 ?

在使用manipulate之前,将xy列表合并到数据帧中是一个好主意。我还把你的POSIXct类切换到Date,因为H:M:S只是"00:00:00"。

> df <- data.frame(x = seq(from=as.POSIXct("2014-01-01"), by=as.difftime(1, units="days"), length.out=100), y = 1:100*2)
> df$x <- as.Date(df$x, format = "%Y-%m-%d")
> with(df, manipulate(plot(x, y, xlim=c(x.min, x.max), xlab = "Date", ylab = "Value"),
+            x.min = slider(as.numeric(min(x)),as.numeric(max(x)), label = "Minimum Date"),
+            x.max = slider(as.numeric(min(x)),as.numeric(max(x)), label = "Maximum Date") 
+            )
+      )

你会注意到你的滑动条值是数字,但你的图形的最终输出是"日期"格式。

最新更新