如何操纵(使用操纵pkg)ggplot2带时间戳轴? [英] How to manipulate (using manipulate pkg) ggplot2 with time-stamped axis?

查看:123
本文介绍了如何操纵(使用操纵pkg)ggplot2带时间戳轴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to produce an interactive plot (using the manipulate package which comes with RStudio) which has time as the x-axis. The user should be able to use sliders on this axis to change the x-limits of the plot, but I can't achieve this. Code reproducing the error is:

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))
)

code>滑块中的错误(最小(时间),最大(时间)):最小值,最大值和初始值都必须为数值

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

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

If any one has any idea on how making such a plot, help would be appreciated.

推荐答案

code> manipulate()和 slider()不能使用日期数据d直接解决办法是将 slider()函数内的最小和最大时间值转换为数字。然后在 scale_x_datetime()中执行相反的操作 - 将 x.min x.max 到POSIXct。滑块将显示数值(而不是日期),但在图形上,您将在x轴上获取日期。

It seems that manipulate() and slider() can't use dates data directly. Workaround would be to convert minimal and maximal time values inside the slider() function to numeric. Then in scale_x_datetime() do the opposite - convert x.min and x.max to POSIXct. Slider will display numeric values (not dates) but on the graph you will get dates on x axis.

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)))
)

这篇关于如何操纵(使用操纵pkg)ggplot2带时间戳轴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆