绘制年度计数的直方图

问题描述 投票:0回答:3

我有一个由一栏组成的csv文件。该列显示在网站上发布的日期。我想绘制一个直方图,以查看多年来的帖子数量如何变化。该文件包含年份(2012年至2016年),由11,000行组成。

文件样本:

2     30/1/12 21:07
3      2/2/12 15:53
4       3/4/12 0:49
5     14/11/12 3:49
6     11/8/13 16:00
7      31/7/14 8:08
8     31/7/14 10:48
9       6/8/14 9:24
10    16/12/14 3:34

数据类型为数据框class(postsData) [1] "data.frame"

我尝试使用以下strptime函数将数据转换为文本:

formatDate <- strptime(as.character(postsData$Date),format="“%d/%m/%y")

然后绘制直方图

hist(formatDate,breaks=10,xlab="year")

enter image description here

任何提示或建议都会有用。谢谢,

r date strptime
3个回答
1
投票

使用lubridate :: dmy_hm()

我认为[[strptime()与{lubridate}相比过于复杂。

library(lubridate)
d <- c("30/1/12 21:07",
       "2/2/12 15:53",
       "3/4/12 0:49",
       "14/11/12 3:49",
       "11/8/13 16:00",
       "31/7/14 8:08",
       "31/7/14 10:48",
       "6/8/14 9:24",
       "16/12/14 3:34")
d2 <- dmy_hm(d)
d2

返回:

[1] "2012-01-30 21:07:00 UTC"
[2] "2012-02-02 15:53:00 UTC"
[3] "2012-04-03 00:49:00 UTC"
[4] "2012-11-14 03:49:00 UTC"
[5] "2013-08-11 16:00:00 UTC"
[6] "2014-07-31 08:08:00 UTC"
[7] "2014-07-31 10:48:00 UTC"
[8] "2014-08-06 09:24:00 UTC"
[9] "2014-12-16 03:34:00 UTC"

如您所见,lubridate函数返回POSIXct对象。

class(d2)
[1] "POSIXct" "POSIXt" 

接下来,您可以使用lubridate::year()来获取dmy_hm()返回的每个POSIXct对象的年份,并绘制该直方图。

hist(year(d2))

1
投票

这是一种方法。我认为您的日期转换很好,但是您需要计算每年发生的日期数,然后将其计算为直方图。

library(tidyverse)
# generate some data

date.seq <- tibble(xdate = seq(from = lubridate::ymd_hms('2000-01-01 00:00:00'), to=lubridate::ymd_hms('2016-12-31 24:59:59'), length.out = 100))

date.seq  %>%  
  mutate(xyear = lubridate::year(xdate)) %>% # add a column of years
  group_by(xyear) %>% 
  summarise(date_count = length(xdate)) %>%  # Count the number of dates that occur in each year
  ggplot(aes(x = xyear, y = date_count)) +
  geom_col(colour = 'black', fill = 'blue') # plot as a column graph

1
投票

strptime() *没问题,但是format选项用于指定格式。

df1$date <- strptime(df1$date, format="%d/%m/%y %H:%M")

# [1] "2012-01-30 21:07:00 CET"  "2012-02-02 15:53:00 CET" 
# [3] "2012-04-03 00:49:00 CEST" "2012-11-14 03:49:00 CET" 
# [5] "2013-08-11 16:00:00 CEST" "2014-07-31 08:08:00 CEST"
# [7] "2014-07-31 10:48:00 CEST" "2014-08-06 09:24:00 CEST"
# [9] "2014-12-16 03:34:00 CET" 

然后您可能想要使用format()功能

formatDate <- format(df1$date, format="%F")

(或者在这种情况下,使用formatDate <- as.Date(df1$date)更简单)

然后

hist(formatDate, breaks=10, xlab="year")

*积分@MikkoMarttila

数据

df1 <- structure(list(id = 2:10, date = c("30/1/12 21:07", "2/2/12 15:53", 
"3/4/12 0:49", "14/11/12 3:49", "11/8/13 16:00", "31/7/14 8:08", 
"31/7/14 10:48", "6/8/14 9:24", "16/12/14 3:34")), class = "data.frame", row.names = c(NA, 
-9L))
© www.soinside.com 2019 - 2024. All rights reserved.