2014-02-20 94 views
1

我想創建從有一些數據類別缺少一些數據週期(月)的,例如彙總數據集GGPLOT2 :: geom_area圖:增加對geom_area缺失data.frame值(GGPLOT2)

require(ggplot2) 
set.seed(1) 
d = data.frame(x = rep(1:10,each=4), y = rnorm(40,10), cat=rep(c('A','B','C','D'), 10)) 
(d = d[-sample(1:40,10),]) # remove some rows 
ggplot(d, aes(x, y, fill=cat)) + geom_area() 

enter image description here

Ggplot的堆積區域圖對缺失值沒有很好的反應,所以我們似乎需要在data.frame中添加零條目。我認爲最好的方式(除非有更好的建議?)是reshape2::dcast它將NA轉換爲零並重新整形。但我無法弄清楚正確的公式。感謝理解重塑的人的幫助(2)。

require(reshape2) 
dcast(d, x ~ cat) # right direction but missing the data 
    x A B C D 
1 1 A B C D 
2 2 <NA> B C <NA> 
3 3 A B C D 
4 4 <NA> B C <NA> 
5 5 A <NA> C D 
6 6 A B C D 
7 7 <NA> B C <NA> 
8 8 A B C D 
9 9 <NA> B <NA> D 
10 10 A B <NA> D 
+0

仍然是有用的,有重塑的解決方案在某些點張貼在這裏,如果任何人有傾斜度.. – geotheory

回答

2
p.data<-merge(d,expand.grid(x=unique(d$x),cat=unique(d$cat),stringsAsFactors=F),all.y=T) 
p.data$y[is.na(p.data$y)]<-0 
ggplot(p.data, aes(x, y, fill=cat)) + geom_area() 

enter image description here

+0

感謝特洛伊快速響應。比我的解決方案更優雅!我會更新問題標題以反映。 – geotheory