【问题标题】:ggplot2 and chron barplot of time data scale_x_chron时间数据scale_x_chron的ggplot2和chron barplot
【发布时间】:2014-04-18 03:29:24
【问题描述】:

我有很多次,想在条形图中绘制每次的频率

library(ggplot2)
library(chron)
test <- data.frame(times = c(rep("7:00:00",4), rep("8:00:00",3), 
                         rep("12:00:00",1), rep("13:00:00",5)))
test$times <- times(test$times)
test
      times
1  07:00:00
2  07:00:00
3  07:00:00
4  07:00:00
5  08:00:00
6  08:00:00
7  08:00:00
8  12:00:00
9  13:00:00
10 13:00:00
11 13:00:00
12 13:00:00
13 13:00:00

选择binwidth的值来表示分钟

p <- ggplot(test, aes(x = times)) + geom_bar(binwidth=1/24/60)
p + scale_x_chron(format="%H:%M")

如您所见,刻度在 x 轴上加一小时:

我感觉这与时区有关,但我无法确定:

Sys.timezone()
[1] "CET"

编辑: 感谢@shadow 的评论

更新:

如果我先运行Sys.setenv(TZ='GMT'),它会完美运行。问题出在times() 函数中。我自动将时区设置为GMT,如果我正在绘制 x 轴,ggplot 会注意到我的系统时区是CET,并在绘图上增加一小时。 现在如果我将我的系统时区设置为GMT,ggplot 不会增加一个小时。

【问题讨论】:

标签: r time ggplot2 chron


【解决方案1】:

与时区无关,唯一的问题是format中,%m代表月份,%M代表分钟。所以以下将起作用

p + scale_x_chron(format="%H:%M") 

【讨论】:

  • 感谢您注意到错误但仍然无法正常工作:imgur.com/yHvxQxr。例如,营业时间仍然是 +1.8:00 而不是 7:00。
  • 尝试将您的 R 系统时区设置为与原始数据相同。例如,对于 UTC 数据,使用Sys.setenv(TZ='GMT')
【解决方案2】:

问题在于times(...) 假定时区是 GMT,然后ggplot 会补偿您的实际时区。这很公平:除非您指定时区,否则时间毫无意义。更大的问题是,似乎无法告诉times(...) 实际时区是什么(如果其他人知道如何做到这一点,我很想知道)。

一种解决方法是使用 POSIXct 并确定您的时区(我的是 EST)。

test <- data.frame(times = c(rep("7:00:00",4), rep("8:00:00",3), 
                             rep("12:00:00",1), rep("13:00:00",5)))
test$times <- as.POSIXct(test$times,format="%H:%M:%S",tz="EST")
p <- ggplot(test, aes(x = times)) + geom_bar(binwidth=60,width=.01)

binwidth=60 是 60 秒。

【讨论】:

  • 是否可以将scale_x_... 用于POSIXTct,比如设置限制?因为每次我使用scale_x_datetime 时,日期都会出现,我只是想限制我的 x 轴而不出现日期。这是我改用chron-package 的原因之一。
  • 您可以添加scale_x_datetime(labels=date_format("%H:%M")),但在这种情况下不需要。
猜你喜欢
  • 1970-01-01
  • 2017-11-22
  • 1970-01-01
  • 2021-01-16
  • 2016-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多