6

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

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 不会增加一个小时。

4

2 回答 2

6

问题是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 秒。

于 2014-03-13T16:47:58.607 回答
2

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

p + scale_x_chron(format="%H:%M") 
于 2014-03-13T12:58:37.503 回答