Reputation: 3
I have a vector containing time. I want to know the frequency of time in each hour. vector looks like this
head(time_col)
[1] "2021-11-23 09:00:00 GMT" "2021-11-23 13:55:00 GMT"
[3] "2021-11-23 01:25:00 GMT" "2021-11-23 01:50:00 GMT"
[5] "2021-11-23 02:25:00 GMT" "2021-11-23 01:30:00 GMT"
hist(time_col,"hours",main = "Density of accidents in each hour" , xlab = "hour" , ylab =
"density",col="green")
I want a frequency histogram
Upvotes: 0
Views: 538
Reputation: 3083
Your data:
df <- data.frame(time_col=c("2021-11-23 09:00:00 GMT",
"2021-11-23 13:55:00 GMT",
"2021-11-23 01:25:00 GMT",
"2021-11-23 01:50:00 GMT",
"2021-11-23 02:25:00 GMT",
"2021-11-23 01:30:00 GMT") )
Load libraries:
library(lubridate) # for date-time manipulation
library(tidyverse) # for the handy '%>%', mutate() and summarise()
library(ggplot2) # for plotting
Count occurrences by hour
df %>% mutate(time_col = ymd_hms(time_col)) %>%
mutate(hour = hour(time_col)) %>%
group_by(hour) %>% summarise(freq = n()) -> hour_freqs
ggplot2 approach for plotting:
ggplot(hour_freqs, aes(x=hour, y=freq)) +
geom_bar(fill = 'green', stat='identity')
For base R, you could do something like this:
barplot(hour_freqs$hour, hour_freqs$freq)
axis(2, seq(0, 5, by=1))
Upvotes: 2