R 如何在数据框中每 2 小时绘制一次 ggplot 频率

R how to ggplot frequency every 2 hours in dataframe

我关注数据集:

time          tta    
08:20:00       1
21:30:00       5
22:00:00       1
22:30:00       1
00:25:00       1
17:00:00       5  

我想使用 ggplot 绘制条形图,以便 x 轴每 2 小时(00:00:00,02:00:00,04:00:00 等)和 y-轴的频率为因子 tta(1 和 5)。

x-axis should be 00-01,01-02,... so on

使用 lubridate

中的 floor_date 函数
library(tidyverse)
library(lubridate)

your_df %>% group_by(floor_date(time,"2 hours")) %>% count(tta)

然后 ggplotgeom_col 从那里

我使用 xts 包来解决这个问题,但后来发现它不提供地板时间。因此,我认为 lubridate 在这里更实用,也是因为 ggplot 不能立即理解 xts 对象。这两个包都可以帮助您以多种方式转换时间数据。

使用 xts::align.timelubridate::floor_date 将您的时间转移到 next/previous 全 hour/day/etc。

无论哪种方式,您都可以在将数据传递给 ggplot 之前聚合数据。您可以使用 sum 来总结 tta,或者只使用 length 来计算出现的次数,但在后一种情况下,您还可以在时间序列上使用 geom_histogram只要。您可以小心地将 ggplot 中的条形图移动为 position_nudge 以表示一个时期,而不是仅仅以某个时间点为中心。您应该在图中指定 scale_x_time(labels = ..., breaks = ...)

数据:

time <- c(
  "08:20:00",
  "21:30:00",
  "22:00:00",
  "22:30:00",
  "00:25:00",
  "17:00:00"
)
time <- as.POSIXct(time, format = "%H:%M:%S")
tta <- c(1, 5, 1, 1, 1, 5)

使用xts:

library(xts)
myxts <- xts(tta, order.by = time)
myxts_aligned <- align.time(myxts, n = 60*60*2)  # shifts all times to the next full
# 2 hours
myxts_agg <- period.apply(myxts_aligned,
                           INDEX = endpoints(myxts, "hours", 2),
                           FUN = sum)  # sums up every two hours
require(ggplot2)
ggplot(mapping = aes(x = index(myxts_agg), y = myxts_agg[, 1])) +
  geom_bar(stat = "identity",
           width = 60*60*2,  # one bar to be 2 hours wide
           position = position_nudge(x = -60*60),  # shift one hour to the left
           # so that the bar represents the actual period
           colour = "black") +
  scale_x_time(labels = function(x) strftime(x, "%H:%M"),
               breaks = index(myxts_agg)) +  # add more breaks manually if you like
  scale_y_continuous()  # to escape the warning of ggplot not knowing
  # how to deal with xts object

使用lubridate:

require(lubridate)
require(tidyverse)
mydf <- data.frame(time = time, tta = tta)
mydf_agg <-
  mydf %>%
    group_by(time = floor_date(time, "2 hours")) %>%
    summarise(tta_sum = sum(tta), tta_freq = n())
ggplot(mydf_agg, aes(x = time, y = tta_sum)) +
  geom_bar(stat = "identity",
           width = 60*60*2,  # one bar to be 2 hours wide
           position = position_nudge(x = 60*60),  # shift one hour to the *right*
           # so that the bar represents the actual period
           colour = "black") +
  scale_x_time(labels = function(x) strftime(x, "%H:%M"),
               breaks = mydf_agg$time)  # add more breaks manually if you like

毕竟大同小异:

library(lubridate)
library(ggplot2)

确保时间戳的 class 是 POSxx

> class(df$timestamp)
[1] "POSIXct" "POSIXt" 

然后使用scale_x_datetime函数如下

gg +
scale_x_datetime(expand = c(0, 0), breaks=date_breaks("1 hour"), labels=date_format("%H:%M")) 

在这种情况下,它将 space x 轴上的制动器,每隔一小时,标签看起来 09:00 例如。