在R中创建一个多月的情节

时间:2017-04-18 12:21:41

标签: r plot

这是我的DF的一个例子。

count month 
3     2014-10-01
4     2014-15-01
3     2014-13-02
12    2014-14-02
12    2014-18-04

我正在尝试在R中生成一个图表,它给出了y轴上的计数。我希望在x轴上有几个月,但是我无法弄清楚如何将所有1月份的月份组合在一起,2月份在一起......等等。

> likes <- plot(seq_along(DF$month),DF$count, type = "l",axes = FALSE, lab = "", lab = "Counts")

有谁知道如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

基本上,您希望按月汇总。但是,这不会给你一个时间序列。它会给你有序的因素。这是如何绘制的。我使用summarisedplyr按月lubridate开始。然后对于x轴,我将月份因子转换为数字,但我没有绘制它(xaxt="n")。我之后使用axis以正确的格式将其添加回来。

df1 <- read.table(text="count month
3     2014-10-01
4     2014-15-01
3     2014-13-02
12    2014-14-02
12    2014-18-04",header=TRUE,stringsAsFactors=TRUE)

library(dplyr);library(lubridate)
DF <- df1%>%
group_by(month=month(ydm(month), label = TRUE))%>%
summarise(count=sum(count))

plot(as.numeric(DF$month),DF$count, type = "l",xaxt="n",main = "Counts")
axis(side=1,at=as.numeric(DF$month),labels=DF$month)

enter image description here

答案 1 :(得分:0)

或基础R和ggplot2解决方案:

# date object
d$month2 <- as.Date(as.character(d$month),  "%Y-%d-%m")
> str(d)
'data.frame':   5 obs. of  3 variables:
  $ count : int  3 4 3 12 12
$ month : Factor w/ 5 levels "2014-10-01","2014-13-02",..: 1 4 2 3 5
$ month2: Date, format: "2014-01-10" "2014-01-15" "2014-02-13" "2014-02-14" ...

# per month
res <- aggregate(d$count, list(months(d$month2)), sum)
# again a date object
res$month <- as.Date(paste0("01-", res$Group.1, "-2014"), "%d-%B-%Y")
# plot
ggplot(res, aes(x= month, y=x)) +
  geom_point() + geom_line() + 
  scale_x_date(date_minor_breaks = "1 month",date_labels = "%B")

enter image description here

您还可以尝试同时包含原始数据作为点和每个条形图的计数:

ggplot(d, aes(x= month2, y=count)) +
  geom_point(col="red") + 
  scale_x_date(date_minor_breaks = "1 month",date_labels = "%B") +
  geom_bar(data = res, aes(x= month, y=x),stat = "identity", position = 'identity',width=0.5)

enter image description here

答案 2 :(得分:0)

没有额外软件包的解决方案,引入了月份的开头(或中间带有-15):

df <- data.frame(count=c(3,4,3,12,12), day=c("2014-10-01", "2014-15-01", "2014-13-02", "2014-14-02", "2014-18-04"))

df$day<-as.Date(df$day, format="%Y-%d-%m")
df$month<-as.Date(format(df$day, "%Y-%m-01"))
df2<-aggregate(count~month, data=df, FUN=sum)
plot(df2$month, df2$count, typ="o")`