【问题标题】:Timestamp in R plotR图中的时间戳
【发布时间】:2021-01-28 09:21:23
【问题描述】:

时间戳数据在chr中如下:

posted_at: chr  "2012-01-29 19:48:33" "2012-02-02 15:53:13" "2012-10-24 17:11:40" "2014-07-12 17:00:00" ...
   [1] "2012-01-29 19:48:33" "2012-02-02 15:53:13" "2012-10-24 17:11:40" "2014-07-12 17:00:00" "2014-07-31 08:08:31"
   [6] "2014-07-31 10:48:25" "2014-08-06 09:24:38" "2015-06-16 15:55:28" "2015-06-16 19:56:28" "2015-06-25 17:20:29"
  [11] "2015-06-26 18:28:31" 

我尝试使用 strptime() 进行转换:

tweet_text$posted_at <- strptime(trump_text$posted_at, "%Y-%m-%d %H:%M:%S")

转换如下:

posted_at: POSIXlt, format: "2012-01-29 19:48:33" "2012-02-02 15:53:13" "2012-10-24 17:11:40" "2014-07-12 17:00:00" ...
   [1] "2012-01-29 19:48:33 AEDT" "2012-02-02 15:53:13 AEDT" "2012-10-24 17:11:40 AEDT" "2014-07-12 17:00:00 AEST"
   [5] "2014-07-31 08:08:31 AEST" "2014-07-31 10:48:25 AEST" "2014-08-06 09:24:38 AEST" "2015-06-16 15:55:28 AEST"
   [9] "2015-06-16 19:56:28 AEST" "2015-06-25 17:20:29 AEST" "2015-06-26 18:28:31 AEST" "2015-07-01 15:58:41 AEST"
  [13] "2015-07-01 18:05:15 AEST

如何使用 hist() 根据年份和计数以及其他不同的组合绘制此时间戳数据。

【问题讨论】:

  • 你可以使用barplot(table(format(trump_text$posted_at, '%Y')))

标签: r ggplot2 timestamp data-visualization histogram


【解决方案1】:

POSIXlt 类中已有年份组件,显示自 1900 年以来的年数。您可以将 1900 添加到年份并在 hist 中使用。

hist(trump_text$posted_at$year + 1900)

使用ggplot2 你可以做到:

library(dplyr)
library(ggplot2)

trump_text %>%
  mutate(year = format(posted_at, '%Y')) %>%
  ggplot() + aes(year) + geom_histogram(stat = 'count')

您可以根据自己的选择自定义/更新情节。

【讨论】:

  • 必须在 hist() 中指定 'breaks' 我得到这个错误的 break
  • 抱歉,应该是hist(trump_text$posted_at$year + 1900)。我已经更新了答案。
【解决方案2】:

我们可以使用table 对从日期时间对象中提取的“年份”进行频率计数,然后执行barplothist。没有使用外部包

hist(as.numeric(format(trump_text$posted_at, '%Y')))

使用可重现的示例

v1 <- as.POSIXlt(sample(seq(Sys.time(), length.out = 20, by = 'year'), 200, replace = TRUE))
hist(as.numeric(format(v1, '%Y')))

-输出


或者另一个选项是tablebarplot

barplot(table(format(v1, '%Y')))

或使用tidyverse

library(dplyr)
library(lubridate)
library(ggplot2)
tibble(v1 = v1) %>%
     mutate(year = year(v1)) %>%
     ggplot(aes(year)) +
     geom_histogram(stat = 'count')

-输出

【讨论】:

  • 我特别想找 hist()
  • @EmmaVaze 然后您可以将barplot 更改为hist
猜你喜欢
  • 2016-05-16
  • 2011-10-18
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 2010-12-30
  • 2021-07-16
  • 1970-01-01
相关资源
最近更新 更多