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/