是否有定义R中时间变量的函数?

时间:2019-11-01 20:24:05

标签: r ggplot2 time-format

我有时间变量和其他变量。我想将我的第一个变量定义为时间,并使用ggplot对其他两个变量进行时间绘制。

我没有尝试任何代码,因为我坚持如何弄清楚自己想要什么。但是,这里有一个(想法代码),它可以模仿我想要的内容,在此之前,我的数据有15行:

data <- structure(list(ATime = structure(1:15, .Label = c("00:00", "00:05",
                                                   "00:10", "00:15", "00:20", "00:25", "00:30", "00:35", "00:40", 
                                                   "00:45", "00:50", "00:55", "01:00", "01:05", "01:10", "01:15", 
                                                   "01:20", "01:25", "01:30", "01:35", "01:40", "01:45", "01:50", 
                                                   "01:55", "02:00", "02:05", "02:10", "02:15", "02:20", "02:25"), class = "factor"), 
                                                      ASpeed5 = c(34, 40, 38, 55, 56, 60, 66, 49, 48, 29, 67, 78, 
                                                      39, 53, 73), BSpeed5 = c(23, 46, 63, 64, 72, 61, 49, 48, 
                                                      63, 68, 62, 27, 35, 45, 59)), row.names = c(NA, 15L), class = "data.frame")


data$ATime <- as.time(data$ATime)
ggplot(data, aes(x = ATime, y1 = ASpeed5, y2 = BSpeed5))+
  geom_line(color = y1, y2)

我希望每条速度(y轴)相对于时间(x轴)都有两条不同颜色的线

2 个答案:

答案 0 :(得分:2)

这是一个基本的R示例,但是如果您经常工作,我建议您使用lubridate软件包。在此示例中,我将ATime变量转换为Date类。如果使用真实数据,您将需要设置自己的时区(tz),但是我在这里默认使用标准时间。

data$ATime <- as.POSIXct(as.character(data$ATime), format="%R", tz="UTC")

data %>% 
  ggplot(aes(x=ATime)) + 
  geom_line(aes(y=ASpeed5, col=1)) +
  geom_line(aes(y=BSpeed5, col=2)) +
  ylab("Speed") + xlab("Time")

enter image description here

编辑以显示数据的子集

要显示数据的子集,可以使用过滤器。在这种情况下,如果时间“小于” 00:10:00,我将调用所有数据。像所有条件语句一样,它的读数大于或小于,但是当变量为日期格式时,您可以将其视为早于或晚于。

data %>% 
  filter(ATime <= "2019-11-01 00:10:00") %>% 
  ggplot(aes(x=ATime)) + 
  geom_line(aes(y=ASpeed5, col=1)) +
  geom_line(aes(y=BSpeed5, col=2)) +
  ylab("Speed") + xlab("Time")

新编辑可显示带有指定轴刻度的完整24小时窗口enter image description here

您的评论听起来像是您想通过设定的休息时间来可视化整个24小时周期。您没有指定间隔,所以我选择4小时。该图像缩放比例很差,因为数据仅在第一个小时出现。请确保为可视化使用适当的比例。

data$ATime <- as.POSIXct(as.character(data$ATime), format="%R", tz="UTC")
fullday <- as.POSIXct(c("00:00", "24:00"), format="%R", tz="UTC")

data %>% 
  ggplot(aes(x=ATime)) + 
  geom_line(aes(y=ASpeed5, col=1)) +
  geom_line(aes(y=BSpeed5, col=2)) +
  scale_x_datetime(limits = fullday, breaks="4 hours", date_labels = "%R") +
  theme(axis.text.x = element_text(angle = 45, vjust=1, hjust=1)) +
  ylab("Speed") + xlab("Time")

enter image description here

答案 1 :(得分:0)

hms包对于处理时间很有用

data %>% 
  mutate(ATime = as.character(ATime)) %>% # easier if character rather than factor
  mutate(xtime = hms::parse_hm(ATime)) %>% 
  gather(-ATime, -xtime, key = 'AB', value = 'Speed') %>% 
  ggplot(aes(x = xtime, y = Speed, colour = AB)) +
  geom_point() +
  geom_line() +
  scale_colour_hue(l=40) +. # make the default colours a little nicer
  labs(x = 'Time')

enter image description here