首页 文章

具有多个变量R的比例堆叠条形图

提问于
浏览
-1

我在R看到一张 table . 列是男性和女性 . 行是4个变量,都是no和yes . 这些值实际上是比例 . 因此,在第1列中,第1行和第2行中的值之和总计为1,因为这是变量1的比例为“是”和“否”的总和 .

propvars
              prop_sum_male prop_sum_female
1_no          0.90123457      0.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(propvars)

这给了我这个:

barplot(propvars)

但正如你所看到的,男性和女性之间的区别是正确的,但他把所有变量放在一起 . 对于4个变量,我需要彼此相邻的4个不同的条,每个条表示是/否堆叠在彼此之上 . 所以Y轴应该像现在一样从0-1而不是0-4 .

关于如何做到这一点的任何提示?

1 回答

  • 2

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

    DATA & CODE

    mydf <- structure(list(prop_sum_male = c(0.90123457, 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

相关问题