2014-11-04 134 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