2017-04-21 95 views
0

我想創建一個條形圖,顯示條形圖y軸中某個日期的日期條目數和圖形x軸上的日期。同時,我想將該欄分爲「是」和「否」部分。R:在ggplot2中使用條形圖中的日期

Date,Hungry 
Friday, March 24, 2017 2:33:46 PM,Yes 
Friday, March 24, 2017 3:39:46 PM,No 
Friday, March 24, 2017 4:39:46 PM,Yes 
Friday, March 24, 2017 5:39:46 PM,No 
Friday, March 24, 2017 6:39:46 PM,Yes 
Friday, March 24, 2017 7:39:46 PM,Yes 
Saturday, March 25, 2017 9:41:00 AM,Yes 
Saturday, March 25, 2017 10:41:00 AM,Yes 
Saturday, March 25, 2017 11:41:00 AM,No 
Saturday, March 25, 2017 13:41:00 AM,No 
Saturday, March 25, 2017 14:41:00 AM,No 
Saturday, March 25, 2017 15:41:00 AM,Yes 
Saturday, March 25, 2017 16:41:00 AM,Yes 

在總共有三月(3Yes/3NO)的25 6個日期條目,並在3月26(4Yes/3NO)7個日期條目。導致像這樣的圖表:

Hungry 
^ 
| 
| 
| 
| 
9| 
|    _ 
| _   |n| 
| |n|  |o| 
5| |o|  |_| 
| |_|  |y| 
| |y|  |e| 
| |e|  |s| 
1|__|s|________|_|__________> 
          Date 

    2   2    
    4   5    
    M   M    
    A   A 
    R   R 
    C   C 
    H   H 

對不起,問這個看似簡單的問題。

編輯。 Adam Quek讓我提供一些數據dput。以下是幾行:

dat <- structure(list(Date = structure(1:4, .Label = c("Friday, March 24, 2017 4:39:46 PM", 
"Friday, March 24, 2017 7:21:33 PM", "Friday, March 24, 2017 7:21:51 PM", 
"Friday, March 24, 2017 7:22:00 PM", "Friday, March 24, 2017 7:22:14 PM", 
"Saturday, March 25, 2017 8:00:10 AM", "Saturday, March 25, 2017 8:00:25 AM", 
"Saturday, March 25, 2017 8:00:46 AM", "Saturday, March 25, 2017 8:01:02 AM", 
"Saturday, March 25, 2017 8:01:20 AM", "Saturday, March 25, 2017 8:01:37 AM", 
"Saturday, March 25, 2017 8:01:50 AM"), class = "factor"), Hungry = structure(c(2L, 
1L, 2L, 1L), .Label = c("No", "Yes"), class = "factor")), .Names = c("Date", 
"Hungry"), row.names = c(NA, 4L), class = "data.frame") 

回答

1

下面是繪製您需要的快捷方式。

library(ggplot2) 
ggplot(dat, aes(date, fill=as.factor(hungry))) + 
     geom_bar() 

enter image description here

我重拍的數據爲:

dat <- structure(list(date = structure(c(17249, 17249, 17249, 17249, 
17249, 17249, 17250, 17250, 17250, 17250, 17250, 17250, 17250 
), class = "Date"), hungry = structure(c(2L, 1L, 2L, 1L, 2L, 
2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L), .Label = c("No", "Yes"), class = "factor")), class = "data.frame", .Names = c("date", 
"hungry"), row.names = c(NA, -13L)) 

編輯:

與新的示例數據附加輸入:

(ⅰ)變更日期到一個可讀的日期格式R.檢查R幫助文件爲strptime日期/時間格式

dat$date <- as.Date(dat$Date, "%A, %B %d, %Y %X") 

(ii)繪製與上述相似的ggplot。

ggplot(dat, aes(date, fill=Hungry)) + 
     geom_bar() 

enter image description here

+0

謝謝您的回覆:-)你提供的圖形正是我要尋找和你建議的代碼獲得期望的結果上面的「最小工作示例」。不幸的是,我無法使用它,因爲我有大量的數據,我不能用這種方式手動更改它。 – Phhilip

+0

您是否能夠首先在R中讀取您的數據?我無法讀取您提供的數據,因爲它不是一種典型的以逗號分隔的或製表符分隔的格式(這就是爲什麼我必須手動輸入它們的原因)。也許如果你可以爲你的數據框輸入數據,那麼我可以幫助它運行。 –

+0

再次感謝您的快速回復。我提取了幾行數據集,並在問題中添加了一個「輸入」。希望這是你要求的。 – Phhilip