2017-05-05 41 views
0

当绘制分类变量小的倍数,我用下面的代码:上ggplot的子组使用频率/ facet_wrap()

ggplot(raw, aes(x = income)) + 
    geom_bar(aes(y = ..count../sum(..count..), fill = factor(..x..))) + 
    facet_wrap("workclass") 

然而,对于每个包好,它给我的当前数据点的频率上数据集的总大小,不仅仅在facet_wrap子集中。

我需要在这段代码中做些什么改变才能让count只在face_wrap子集中运行?

回答

1

您需要重新构造数据(即在致电ggplot()之前通过workclass组创建百分比数据)。这是一个data.table的方法来做到这一点。

require(data.table) 
rawdt <- data.table(raw) 
new_data <- rawdt[, .N, by = .(income, workclass)][, classN := sum(N), by = workclass][, y := N/classN] 
ggplot(new_data, aes(x = income, y = y)) + geom_bar(stat = "identity") + 
    facet_wrap(~workclass) 
+0

这工作不正常。不仅它不是全频带,而且轴现在处于绝对计数单位而不是频率百分比。 –

+0

我在我的代码中发现一个错误并修复。 –

+0

向量分配中的[.data.table'(rawdt [,.N,by =。(income,workclass)],':='(classN,:无效类型/长度(内建值/ 17)的错误 –

0

你可以使用dplyr

例如,你对mtcars数据集代码:

ggplot(mtcars,aes(x = gear)) + 
    geom_bar(aes(y = ..count../sum(..count..), fill = factor(..x..))) + 
    facet_wrap("cyl") 

再形成像@ amatsuo_net的解决方案的数据,但在dplyr

library(dplyr) 
mtcars2 <- inner_join(mtcars %>% 
         group_by(cyl) %>% 
         summarise(total = n()), 
         mtcars %>% 
         group_by(gear,cyl) %>% 
         summarise(sub_total = n()), 
        by = "cyl") %>% 
      mutate(prop = sub_total/total) 

ggplot(data = mtcars2, aes(x = gear,y=prop)) + 
    geom_bar(stat = "identity") + 
    facet_wrap(~cyl)