使用ggplot绘制直方图,统计各时间戳对应数据行数
Perfect, since you've already converted your Timestamp variable to POSIXct format, moving to ggplot2 for your hourly count histogram is straightforward. Here are a couple of practical approaches that align with what you were doing with base R's hist():
Option 1: Directly use geom_histogram (closest to base R's workflow)
This method lets ggplot handle binning and counting automatically, just like hist() does. We'll set the bin width to 3600 seconds (1 hour) and tweak the x-axis to display hourly ticks clearly:
# Load ggplot2 if you haven't already library(ggplot2) # Create the hourly histogram ggplot(data.frame(timestamp = datas), aes(x = timestamp)) + geom_histogram(binwidth = 3600, fill = "grey", color = "white") + scale_x_datetime( date_breaks = "1 hour", date_labels = "%Y/%m/%d %H:%M" ) + labs( title = "Datas de Realização do Inquérito", x = "Data", y = "Nº de Inquéritos Realizados" ) + theme(axis.text.x = element_text(angle = 45, hjust = 1)) # Rotate x-labels to avoid overlap
Option 2: Precompute hourly counts (more flexible for customization)
If you want greater control over your data before plotting, you can first calculate the number of entries per hour using dplyr and lubridate, then visualize the precomputed counts:
# Load required packages library(ggplot2) library(dplyr) library(lubridate) # For easy time rounding # Calculate hourly entry counts hourly_data <- datas %>% as.data.frame() %>% rename(timestamp = ".") %>% mutate(hour_start = floor_date(timestamp, "hour")) %>% # Round each timestamp to its hour start count(hour_start) # Plot the precomputed counts ggplot(hourly_data, aes(x = hour_start, y = n)) + geom_bar(stat = "identity", fill = "grey") + scale_x_datetime( date_breaks = "1 hour", date_labels = "%Y/%m/%d %H:%M" ) + labs( title = "Datas de Realização do Inquérito", x = "Data", y = "Nº de Inquéritos Realizados" ) + theme(axis.text.x = element_text(angle = 45, hjust = 1))
Both options will produce a histogram that matches the behavior of your original hist() call, while giving you the customization flexibility that ggplot2 is known for.
内容的提问来源于stack exchange,提问作者davidbaguetta

