You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:47:32