【问题标题】:ggplot: relative frequencies of two groupsggplot:两组的相对频率
【发布时间】:2012-06-04 20:45:57
【问题描述】:

我想要这样的情节,除了每个方面的总和为 100%。现在组 M 是 0.05+0.25=0.30 而不是 0.20+0.80=1.00。

df <- rbind(
    data.frame(gender=c(rep('M',5)), outcome=c(rep('1',4),'0')),
    data.frame(gender=c(rep('F',10)), outcome=c(rep('1',7),rep('0',3)))
)

df

ggplot(df, aes(outcome)) +
    geom_bar(aes(y = (..count..)/sum(..count..))) +
    facet_wrap(~gender, nrow=2, ncol=1) 

(使用 y = ..density.. 会产生更差的结果。)

【问题讨论】:

标签: r ggplot2


【解决方案1】:

这是另一种方式

ggplot(df, aes(outcome)) +
    geom_bar(aes(y = ..count.. / sapply(PANEL, FUN=function(x) sum(count[PANEL == x])))) +
    facet_wrap(~gender, nrow=2, ncol=1) 

【讨论】:

  • 我喜欢它的简短,但是当我尝试从 facet 切换到 position=dodge 时,所有组(而不是组内)的高度总和为 100%
  • 有什么方法可以将它扩展到一个在面板中分为多面和分组的情节?
  • @Matthew Plourde:很好的答案。您介意在答案中解释..count.. 的用法吗?它只是情节命名空间中的一个值吗?
【解决方案2】:

我通常通过简单地预先计算 ggplot2 之外的值并使用 stat = "identity":

来做到这一点
df1 <- melt(ddply(df,.(gender),function(x){prop.table(table(x$outcome))}),id.vars = 1)

ggplot(df1, aes(x = variable,y = value)) +
    facet_wrap(~gender, nrow=2, ncol=1) +
    geom_bar(stat = "identity")

【讨论】:

  • 这是正确的。我希望对看似相对常见的图表有一个更简单的答案。 :)
  • @andrew - 我这样做很多。制作自己的geom 相对容易,这将是对 ggplot2 内置工具的一个很好的补充。
  • @Chase 我可能是错的,但我认为这需要的不仅仅是一个新的几何图形,因为(我认为)美学被映射到变量在完成刻面之前。所以我认为这可能是geom上游的一种设计特征方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-17
  • 2018-09-04
  • 2022-08-18
  • 2018-10-25
  • 1970-01-01
  • 2017-04-30
  • 1970-01-01
相关资源
最近更新 更多