2014-11-04 133 views
-1

我在R看起来像这样。列是男性和女性。行是4个变量,其中一个是no &是的。这些值实际上是比例。因此,在第1列的第1行中值和2总结了1总和,因为这是比例是&不变量1.具有多个变量的比例叠加barplot R

propvars 
       prop_sum_male prop_sum_female 
1_no   0.9.96296296 
1_yes   0.09876543  0.03703704 
2_no   0.88750000  0.96296296 
2_yes   0.11250000  0.03703704 
3_no   0.88750000  1.00000000 
3_yes   0.11250000  0.00000000 
4_no   0.44444444  0.40740741 
4_yes   0.55555556  0.59259259 

总和我想创建为这些4个变量的堆叠barplot 。

我用

barplot(propvars) 

,给了我这样的:

barplot(propvars)

但你可以看到男性&女性之间的区别是正确的,但他把每个上面所有变量其他。而且我需要4个不同的酒吧为4个变量,每个酒吧代表是/否堆叠在一起。所以Y轴应该像现在一样从0-1变为0-4。

任何提示如何做到这一点?

回答

2

这可能会有帮助。我安排了你的数据以绘制图表。我添加了行名作为列。然后,我将数据更改为长格式数据。

DATA & CODE

mydf <- structure(list(prop_sum_male = c(0.9, 0.09876543, 0.8875, 
0.1125, 0.8875, 0.1125, 0.44444444, 0.55555556), prop_sum_female = c(0.96296296, 
0.03703704, 0.96296296, 0.03703704, 1, 0, 0.40740741, 0.59259259 
)), .Names = c("prop_sum_male", "prop_sum_female"), class = "data.frame", row.names = c("1_no", 
"1_yes", "2_no", "2_yes", "3_no", "3_yes", "4_no", "4_yes")) 

library(qdap) 
library(dplyr) 
library(tidyr) 
library(ggplot2) 

mydf$category <- rownames(mydf) 

df <- mydf %>% 
     gather(Gender, Proportion, - category) %>% 
     mutate(Gender = char2end(Gender, "_", 2)) %>% 
     separate(category, c("category", "Response")) 

ggplot(data = df, aes(x = category, y = Proportion, fill = Response)) + 
    geom_bar(stat = "identity", position = "stack") + 
    facet_grid(. ~ Gender) 

enter image description here

+0

如果可能的话,我想用 'barplot' 功能,而不是ggplot的。不过谢谢你的回答。 – user1987607 2014-11-04 14:30:19

+0

然后用男性/女性子集创建两个不同的情节并将它们放在一起。 – 2014-11-04 20:03:40