scale_datetime移动x轴 [英] scale_datetime shifts x axis

查看:66
本文介绍了scale_datetime移动x轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ggplot2绘制一个x轴为"POSIXct"类的时间序列,该时间序列可以工作到一个点.

I am trying to plot a time series that has an x axis of class "POSIXct" using ggplot2, which is working up to a point.

当我尝试使用scale_x_datetime操作x轴中断和标签时,它会在x轴上产生一个月的移位.

When I try to manipulate the x axis breaks and labels using scale_x_datetime it generates a one month shift in the x axis.

任何人都可以解释一下,并提供解决方案吗?

Can anyone explain this, and provide a solution?

示例简化代码:

start <- as.POSIXct("2014/07/01 00:00:00")
end <- as.POSIXct("2014/10/01 23:30:00")
interval <- as.difftime("00:30:00")
df <- data.frame(t=seq(start, end, by="1 day"))
df$v <- sample(1:100, replace=TRUE, nrow(df))

p <- ggplot(data=df, aes(x=t)) +
  geom_line(aes(y=v))

p2 <- p + scale_x_datetime(breaks=date_breaks("1 month"), labels=date_format("%b-%y"))

推荐答案

这是时区问题. date_format默认将时区设置为"UTC",并内部调用format.POSIXct,内部调用as.POSIXlt.发生这种情况:

It's a time zone issue. date_format sets the time zone to "UTC" by default and internally calls format.POSIXct which calls as.POSIXlt internally. There this happens:

as.POSIXlt(start, "UTC")
#[1] "2014-06-30 22:00:00 UTC"

Voilà,不同的月份.

Voilà, a different month.

您可以通过不更改时区来避免这种情况:

You can avoid this by not changing the time zone:

p + scale_x_datetime(breaks=date_breaks("1 month"), 
                     labels=date_format("%b-%y", tz = Sys.timezone(location = TRUE)))

如果在创建POSIXct变量时显式定义了时区(应该),则应在此处传递该时区.

If you explicitly defined a time zone (you should) when creating the POSIXct variable, you should pass this time zone here.

这篇关于scale_datetime移动x轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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