为几何图形区域(ggplot2)添加缺失的data.frame值

为几何图形区域(ggplot2)添加缺失的data.frame值,r,reshape,reshape2,R,Reshape,Reshape2,我想从某些数据周期(月)缺少某些数据类别的摘要数据集创建ggplot2::geom_面积图,例如: 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

我想从某些数据周期(月)缺少某些数据类别的摘要数据集创建ggplot2::geom_面积图,例如:

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()

Ggplot的堆叠面积图对缺失的值没有很好的响应,因此我们似乎需要在data.frame中添加零个条目。我能想到的最好的方法(除非有更好的建议?)是
reforme2::dcast
it,将NA转换为零,然后重新整形。但我想不出正确的公式。感谢理解重塑的人的帮助(2)

require(重塑2)
dcast(d,x~cat)#方向正确但缺少数据
x A B C D
1 A B C D
2 B C
3 A B C D
4 B C
5 A C D
6 A B C D
7 B C
8 A B C D
公元前9年
10 A B D
#展开data.frame

p、 感谢特洛伊的快速反应。比我的解决方案更优雅!我将更新问题标题以反映问题。如果有人愿意,在某个时候将重塑解决方案发布在这里仍然很有用。。
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
# Expand the data.frame
p.data <- merge(d,
                expand.grid(x=unique(d$x),
                            cat=unique(d$cat),
                            stringsAsFactors=F),
                all.y=T)

# Fill NA values with zeros
p.data$y[is.na(p.data$y)] <- 0

# Plot the graph
ggplot(p.data, aes(x, y, fill=cat)) +
    geom_area()