绘制格式为 hh:mm:ss 的字符串列作为直方图,以获取 R 中上午 12 点到下午 3 点之间的观察计数

Plotting a string column of format hh:mm:ss as histogram to get count of observation between 12 AM and 3 PM in R

我有一个数据集,其中有一列格式为 hh:mm:ss。我想基于此列创建一个直方图,以便我可以在 R 中可视化上午 12 点到下午 3 点之间的观察次数。

plot_ly(x = (as.numeric(data$Time) * 1000), type = "histogram") %>% 
  layout(xaxis=list(type="date", tickformat="%H:%M:%S"))

我尝试使用 Plotly 绘图,但 x 轴的格式与预期的不同。请给点建议。

一种方法是使用 hms 库

library("hms")

由于没有提供数据,我生成了一些随机数据以便于理解。 as_hms() 函数将值转换为具有自定义 class

的 difftime 向量
Count <- c(10,20,30,100,110,110,20,30,50,30)
Time <- c('12:02:01','12:07:38','12:30:42','12:57:21','13:01:09','13:38:36','13:48:43','13:51:33','14:50:22','14:59:59')

Time = as_hms(c(Time))

data = data.frame(Count, Time)

使用 ggplot,您现在可以轻松地创建包含观察值数量的直方图。如果您明确需要一个 plotly 可视化,您可以使用库 ggplotly 来实现。

p <- ggplot(data=data, aes(x=Time, y=Count)) +
  geom_bar(stat="identity")


ggplotly(p)