首页 > 解决方案 > 在给定其他变量的情况下显示一个变量的存在百分比

问题描述

我目前正在处理一些情节,并且根据我目前的 ggplot2 知识,我遇到了一个我现在无法解决的问题。

我将尝试使用我在 R 中创建的虚构数据来解释我的问题。下面我将 str 命令的输出留在我的虚构数据框中:

'data.frame':   15 obs. of  4 variables:
 $ x: Factor w/ 2 levels "0","1": 2 1 2 1 1 1 2 2 1 2 ...
 $ y: Factor w/ 2 levels "0","1": 1 2 2 1 2 2 2 1 1 1 ...
 $ w: Factor w/ 2 levels "0","1": 2 1 2 2 1 1 1 1 2 2 ...
 $ z: Factor w/ 2 levels "0","1": 2 1 2 2 1 1 2 2 1 2 ...

如您所见,这些都是二分变量。让我们考虑我的因变量是 y。我想做的图是一个条形图,如下图:

我想做的情节。

我真的很想制作这样的情节。另一个像这样的,但也添加了一个 y 流行度条,将自变量(x、w 和 z)上为 1 的组与自变量(x、w 和 z)上为 0 的组进行比较。所以,在第二个想法中,它将是 6 个小节,而不是只有 3 个。但是这两个想法中的任何一个都可以很好地满足我的需要。在此先感谢社区,您总是非常乐于助人。

示例数据:

d <- structure(list(x = structure(c(2L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L), .Label = c("0", "1"), class = "factor"),     y = structure(c(1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L,     2L, 2L, 2L, 1L), .Label = c("0", "1"), class = "factor"),     w = structure(c(2L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L,     1L, 1L, 2L, 2L), .Label = c("0", "1"), class = "factor"),     z = structure(c(2L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 1L,     2L, 1L, 1L, 1L), .Label = c("0", "1"), class = "factor")), row.names = c(NA, -15L), class = "data.frame")

标签: rggplot2plotbar-chart

解决方案


将宽转换为长,然后在 y 为每组一个时获取摘要:

library(data.table)
library(ggplot2)

# wide to long
setDT(d)
plotDat <- melt(d, id.vars = "y"
                )[ , .(yPC = sum(y == "1")/.N * 100),
                   by = .(variable, value)]

ggplot(plotDat, aes(variable, yPC, fill = value)) +
  geom_bar(stat = "identity", position = "dodge")

在此处输入图像描述


推荐阅读