r - 你能在 ggplot2 中对指示变量进行分面分析吗?

标签 r ggplot2

types = c("A", "B", "C")
df = data.frame(n = rnorm(100), type=sample(types, 100, replace = TRUE))
ggplot(data=df, aes(n)) + geom_histogram() + facet_grid(~type)

以上是我平时使用分面的方式。但是,当我有一组作为指示变量的列而不是分类变量时,我可以使用它吗,例如:

df = data.frame(n = rnorm(100), A=rbinom(100, 1, .5), B=rbinom(100, 1, .5), C=rbinom(100, 1, .5))

现在,我之前示例中的“Type”变量不再相互排斥。例如,观察可以是“A 和 B”或“A 和 B 和 C”。但是,对于任何存在 A、B 或 C 的观察结果,我仍然想要一个单独的直方图?

最佳答案

我将使用 tidyr reshape 数据,以便复制不止一个类别的数据。 filter 以删除不需要的情况。

df <- data.frame(
  n = rnorm(100),
  A = rbinom(100, 1, .5),
  B = rbinom(100, 1, .5),
  C = rbinom(100, 1, .5)
)

library("tidyr")
library("dplyr")
library("ggplot2")

df %>% gather(key = "type", value = "value", -n) %>%
  filter(value == 1) %>%
  ggplot(aes(x = n)) +
    geom_histogram() +
    facet_wrap(~type)

关于r - 你能在 ggplot2 中对指示变量进行分面分析吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42461915/

相关文章:

r - 计算R中目录的大小

R xts : transform all 0 values in a time series with the last found value different than 0

r - ggplot 图例 - 更改标签、顺序和标题

r - 将 MASS::fitdistr 按一个因子应用于多个数据

r - 带有特定顺序和百分比注释的 ggplot2 饼图

r - 使用列名称粘贴多个列值

r - 在哪里可以看到 R 版本推出的基本原理和计划?

r - knitr,pandoc:将SVG直接嵌入HTML文档

r - ggplot2 轴文本标签 : subscript + superscript + square brackets

r - 在 qqplot 和 Shiny 中命名图例