2017-04-18 90 views
0

這裏是我的DF的一個例子。在R中創建一個陰謀

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

我試圖產生R A的情節,讓我在y軸上的計數。我想對x軸的幾個月,但我無法弄清楚如何將所有一月月在一起,月月在一起......等

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

有誰知道如何去了解這個?

+0

可以嘗試變換的日期爲[yearmon對象(https://開頭www.rdocumentation.org/packages/zoo/versions/1.7-14/topics/yearmon),然後您可以輕鬆進行分組,因爲它的行爲與一個因素類似。 – cylim

回答

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

+0

謝謝,但是,當我在我的真實數據集上嘗試此代碼時,我得到的是所有計數的總數,而不是僅計算1月,2月,3月......你知道爲什麼嗎? – Ashley

+0

檢查'months(d $ month2)'是否給你帶有不同月份名稱的向量。我想,如果沒有什麼事情會在日期轉換之前出現錯誤。檢查'str(your_data)' – Jimbou

+0

謝謝,我想出了問題。這很好 – Ashley

0

基本上,你想按月彙總。但是,這不會給你一個時間系列。它會給你訂購的因素。以下是如何繪製該圖。我首先使用dplyrlubridate按月份summarise。然後對於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

+0

這就是我要找的,謝謝。當我嘗試運行'DF <- df1%>% group_by(month = month(ydm(month),label = TRUE))%>% summarize(count = sum(count))'我得到這個錯誤:Error:can not coerce type 'closure'到'character'類型的向量 – Ashley

+0

@Ashley假設你指的是你的真實數據,檢查'str(df1)'。日期必須採用日期格式。如果需要,請事先使用'df1 $ month <-as.Date(df1 $ month) –

+0

謝謝。我意識到我在代碼中犯了一個小錯誤。然而,我還有另一個問題,當我在運行group_by和彙總命令後查看我的DF時,我只看到1月份的總數。在我真正的DF中,日期列的標籤是'Month'。我的group_by語句應該是這樣嗎? 'group_by(month = month(ydm(Month),label = TRUE))%>%' – Ashley

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")`