2014-02-20 61 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