2017-02-25 62 views
2
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) 

以上是我通常如何使用facetting。但我可以用它代替分類變量時,我有一組是指示變量,如列:你可以在ggplot2中指示變量嗎?

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

現在從我前面的例子中的「類型」的變量不是相互排斥的。例如,觀察可以是「A和B」或「A和B和C」。但是,我仍然喜歡有個別直方圖來觀察存在A,B或C的任何觀察結果嗎?

回答

2

我會用tidyr重塑數據,以便更多一個類別的數據被複制。 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) 
1

我一直鄙視gather,所以我會添加另一種方法,一個用於data.table球迷。

library(data.table) 
DT <- melt(setDT(df), id= "n", variable = "type")[value > 0] 
ggplot(DT,aes(n)) + geom_histogram() + facet_grid(~type) 

#tidyland 
library(reshape2) 
library(dplyr) 
library(ggplot2) 
df %>% 
    melt(id = "n", variable = "type") %>% 
    filter(value > 0) %>% 
    ggplot(aes(n)) + geom_histogram() + facet_grid(~type) 
相關問題