如何操纵(使用操纵pkg)ggplot2带有时间戳的轴?

时间:2014-03-23 17:59:54

标签: r datetime plot ggplot2 rstudio

我想制作一个交互式图(使用RStudio附带的操作包),它有时间作为x轴。用户应该能够在此轴上使用滑块来更改绘图的x限制,但我无法实现此目的。重现错误的代码是:

require(manipulate)  
df <- data.frame(time=seq(ISOdate(2000,1,1),by="month",length.out=100),y=rnorm(100))

# This would do a standard - non interactive - ggplot
#ggplot(df,aes(x=time,y=y))+  
#geom_line()+  
#scale_x_datetime(limits=c(min(time),max(time)))

# This tries to do the interactive plot
manipulate(  
{ggplot(df,aes(x=time,y=y))+  
geom_line()+  
scale_x_datetime(limits=c(x.min,x.max))},  
x.min=slider(min(time),max(time)),  
x.max=slider(min(time),max(time))
)

返回error in slider(min(time), max(time)) : min, max, and initial must all be numeric values

如果任何人对如何制作这样的情节有任何想法,那么将不胜感激。

1 个答案:

答案 0 :(得分:3)

似乎manipulate()slider()无法直接使用日期数据。解决方法是将time函数中的最小和最大slider()值转换为数字。然后在scale_x_datetime()中执行相反操作 - 将x.minx.max转换为POSIXct。滑块将显示数值(不是日期),但在图表上,您将获得x轴上的日期。

manipulate(  
{ggplot(df,aes(x=time,y=y))+  
   geom_line()+  
   scale_x_datetime(limits=c(as.POSIXct(x.min,origin = "1970-01-01"),
                             as.POSIXct(x.max,origin = "1970-01-01")))},  
x.min=slider(as.numeric(min(df$time)),as.numeric(max(df$time))),  
x.max=slider(as.numeric(min(df$time))+2,as.numeric(max(df$time)))
)