【问题标题】:Adding missing data.frame values for geom_area (ggplot2)为 geom_area (ggplot2) 添加缺失的 data.frame 值
【发布时间】:2014-03-21 08:06:25
【问题描述】:

我想从汇总数据集中创建 ggplot2::geom_area 图,这些数据集在某些数据周期(月)中缺少某些数据类别,例如:

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 中添加零条目。我能想到的最好方法(除非有更好的建议?)是reshape2::dcast 它,将 NA 转换为零并重新整形。但我想不出正确的公式。感谢了解 reshape(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

【问题讨论】:

  • 如果有人愿意的话,在某些时候将重塑解决方案张贴在这里仍然很有用..

标签: r reshape reshape2


【解决方案1】:
# 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()

【讨论】:

  • 感谢特洛伊的快速响应。比我的解决方案更优雅!我将更新问题标题以反映。
猜你喜欢
  • 2021-12-27
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-17
  • 2010-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多