我以下數據集:ř如何ggplot頻率在數據幀每2小時
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
我以下數據集:ř如何ggplot頻率在數據幀每2小時
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
我走近這個用xts
包,但後來發現,它並沒有提供地板時間。因此,我得出結論lubridate
在這裏更實用,也因爲ggplot
不瞭解xts
對象。這兩個軟件包都可以幫助您以多種方式轉換時間數據。
使用xts::align.time
或lubridate::floor_date
將您的時間轉移到下一個/上一個整小時/天等。
無論採用哪種方式,您在將數據傳遞給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
畢竟的allmost相同:
使用來自lubridate
library(tidyverse)
library(lubridate)
your_df %>% group_by(floor_date(time,"2 hours")) %>% count(tta)
的floor_date
功能,然後用geom_col
ggplot
從那裏
謝謝,但我收到錯誤:mutate_impl(.data,dots)錯誤: 沒有適用於'reclass_date'的方法應用於類「c('hms','difftime')」 –
我想你的'時間'列的方式,lubridate不能'floor_date'。你的數據是否跨越多天?如果不是的話,你可以使用時間數據跨越幾年的子字符串 – shuckle
獲取'time'列的前兩位數字,但它不應該扮演任何角色,因爲我將僅使用具有因子變量的時間變量。如何將時間數據分組到兩小時範圍(bin) –
那麼你的問題是什麼?你嘗試了什麼? – user3640617
問:如何繪製tta的頻率使用時間數據每隔兩小時的間隔 –