使用时间在ggplot2中添加一个vline [英] Adding a vline in ggplot2 using time

查看:118
本文介绍了使用时间在ggplot2中添加一个vline的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的示例数据框如下所示。

  set.seed(1234)
df < - data.frame(Date = seq(as.POSIXct(05:00,format =%H :%M),
as.POSIXct(23:00,format =%H:%M),by =hours))
df $计数< - sample 19)
df <-df [-c(4,7,17​​,18),]

#自动生成组并且绘制
idx< - c( 1,diff(df $ Date))
i2 < - c(1,其(idx!= 1),nrow(df)+1)
df $ grp< - rep (a)(aes(group = grp))+
geom_point()

似乎有很多关于堆栈溢出和网页的讨论,时间序列上的vlines。我一直在纠正我的代码,但目前我没有多少运气。



例如,我想在21日下午2点竖线。

  g1 < -  g + geom_vline(xintercept = as.numeric(as.Date(2013-02-21 14: 00:00)))

任何人都可以告诉我如何让它起作用吗?您必须将 as.Date()替换为<$ c $>来替换

解决方案 c> as.POSIXct()因为您还需要时间而不仅仅是日期(函数 as.Date()仅代表日期部分) p>

  g + geom_vline(xintercept = as.numeric(as.POSIXct(2013-02-21 14:00:00)) )

您可以通过查看以下两种情况来查看差异:

  as.Date(2013-02-21 14:00:00)
[1]2013-02-21

as.POSIXct(2013-02-21 14:00:00)
[1]2013-02-21 14:00:00 EET


I am having some problems adding a vertical line to a gplot2 graph.

My example dataframe is listed below.

set.seed(1234)
df <- data.frame(Date=seq(as.POSIXct("05:00", format="%H:%M"), 
                          as.POSIXct("23:00", format="%H:%M"), by="hours"))
df$Counts <- sample(19)
df <- df[-c(4,7,17,18),]

# generate the groups automatically and plot
idx <- c(1, diff(df$Date))
i2 <- c(1,which(idx != 1), nrow(df)+1)
df$grp <- rep(1:length(diff(i2)), diff(i2))
g <- ggplot(df, aes(x=Date, y=Counts)) + geom_line(aes(group = grp)) + 
  geom_point()

There seems to be quite a lot of discussion on stack overflow and the web generally about using vlines on timeseries. I have had a go at rectifying my code but I am not having much luck so far.

Say for example I want a vertical line at 2 pm on the 21st.

g1 <- g + geom_vline(xintercept=as.numeric(as.Date("2013-02-21 14:00:00")))

Could anyone advise me how I might get this to work?

解决方案

You have to replace as.Date() with as.POSIXct() because you also need time not just date (function as.Date() represents only date part).

g + geom_vline(xintercept=as.numeric(as.POSIXct("2013-02-21 14:00:00")))

You can see the difference by looking on those two cases:

 as.Date("2013-02-21 14:00:00")
[1] "2013-02-21"

 as.POSIXct("2013-02-21 14:00:00")
[1] "2013-02-21 14:00:00 EET"

这篇关于使用时间在ggplot2中添加一个vline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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