在R中绘制每天和每月的购买计数

时间:2017-12-03 14:53:18

标签: r plot ggplot2

数据集表示哪一个客户(Cstid =客户ID)在哪一天进行了购买。

我很难找到解决方案来绘制每天和每月的购买数量。

请在下面找到数据集的示例,我总共有7505个观测值。

  "Cstid"  "Date"
1  4195     19/08/17
2  3937     16/08/17
3  2163     07/09/17
4  3407     08/10/16
5  4576     04/11/16
6  3164     16/12/16
7  3174     18/08/15
8  1670     18/08/15
9  1671     18/08/15
10 4199     19/07/14
11 4196     19/08/14
12 6725     14/09/14
13 3471     14/09/13

我已经开始转换Date列:

 df$Date <- as.Date(df$Date, '%d/%m/%Y')

然后使用以下方法计算每个日期的观察次数:

library(data.table)
dt <- as.data.table(df)
dt[,days:=format(Date,"%d.%m.%Y")]
dt1 <- data.frame(dt[,.N,by=days])

试图用:

绘图
plot(dt1$days, dt1$N,type="l")

但是我收到以下错误消息:

Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf

有人可以告诉我该怎么办吗?

2 个答案:

答案 0 :(得分:2)

您需要使用%y(小写)指定2位数年份,以便将Date列从字符转换为类Date

如果ggplot2用于绘图,它也会进行聚合。 geom_bar()默认使用count统计信息。这使我们无法预先计算聚合(计数)。

对于按月汇总,我建议将所有日期映射到每个月的第一天,例如,使用lubridate::floor_date()。这样可以在x轴上保持连续刻度。

所以,完整的代码将是:

# convert Date from character to class Date using a 2 digit year
df$Date <- as.Date(df$Date, '%d/%m/%y')

library(ggplot2)
# aggregate by day
ggplot(df) + aes(x = Date) + 
  geom_bar()

enter image description here

#aggregate by month
ggplot(df) + aes(x = lubridate::floor_date(Date, "month")) + 
  geom_bar()

enter image description here

或者,日期可以映射到字符月,例如"2015-08"。但这会将x轴变为离散比例,不再显示购买之间经过的时间:

# aggregate by month using format() to create discrete scale
ggplot(df) + aes(x = format(Date, "%Y-%m")) + 
  geom_bar()

enter image description here

答案 1 :(得分:1)

#reproduciable data:
df <- data.frame(Cstid=c(4195,3937,2163,3407,4576,3164,3174,1670,1671,4199,4196,6725,3471),
           Date=c('19/08/17','16/08/17','07/09/17','08/10/16','04/11/16','16/12/16','18/08/15','18/08/15',
'18/08/15','19/07/14','19/08/14','14/09/14','14/09/13'))
#convert format:
df$Date <- as.character(df$Date)
Y <- paste('20',sapply(strsplit(df$Date,split = '/'),function(x){x[3]}),sep='')
M <- sapply(strsplit(df$Date,split = '/'),function(x){x[2]})
D <- sapply(strsplit(df$Date,split = '/'),function(x){x[1]})
df$Date <-  as.POSIXct(paste(Y,M,D,sep='-'),format='%Y-%m-%d')
#count per day plot:
days <- unique(df$Date)
dcount <- vector()
for (i in 1:length(days)) {
dcount[i]  <- nrow(df[df$Date==days[i],])
}
library(ggplot2)
ggplot(data=data.frame(days,dcount),aes(x=days,y=dcount))+geom_point()
#count per month plot:
df$month <- months(df$Date)
mon <- unique(df$month)
mcount <- vector()
for (i in 1:length(mon)) {
  mcount[i]  <- nrow(df[df$month==mon[i],])
}
ggplot(data.frame(mon,mcount),aes(x=mon,y=mcount))+geom_point()
相关问题