R 带有多个布尔列的ggplot刻面

R 带有多个布尔列的ggplot刻面,r,ggplot2,boolean,subset,R,Ggplot2,Boolean,Subset,我有一个数据框,其中一列表示日期,一列表示值,还有大约六个布尔列: date value x1 x0 x2 x3 .... 01/1999 2000 TRUE FALSE TRUE FALSE 02/1999 5000 FALSE TRUE FALSE FALSE 02/1999 6000 FALSE TRUE FALSE TRUE 03/1999 500

我有一个数据框,其中一列表示日期,一列表示值,还有大约六个布尔列:

date        value         x1    x0    x2    x3 ....
01/1999     2000          TRUE  FALSE TRUE  FALSE
02/1999     5000          FALSE TRUE  FALSE FALSE
02/1999     6000          FALSE TRUE  FALSE TRUE
03/1999     5000          TRUE  FALSE FALSE TRUE
现在我想为每个列x1,x0绘制每个日期条目的计数…: 通过对数据帧进行子集设置并每次调用ggplot,我可以轻松做到这一点:

ggplot(subset, aes(date)) + geom_bar()

但我想知道是否有一种方法可以生成一个包含面的单一绘图,每个面有6个子绘图,每个子绘图都经过x1、x2、x3=TRUE的过滤。听起来您可能希望将数据帧从宽格式转换为长格式,将所有布尔列收集到一个列中。例如:

library(dplyr)
library(tidyr)

df %>%
  gather(subset.variable, logic, -date, -value) %>%
  filter(logic) %>%
  ggplot(aes(date, value)) +
  geom_point() +                # using geom_point for illustration
  facet_wrap(~subset.variable)

使用的样本数据:

set.seed(123)
n = 200
df <- data.frame(
  date = seq.Date(from = as.Date("1999-01-01"),
                  to = as.Date("1999-01-01") + n - 1,
                  by = 1),
  value = rpois(n, lambda = 2),
  x1 = sample(c(TRUE, FALSE), n, replace = T),
  x2 = sample(c(TRUE, FALSE), n, replace = T),
  x3 = sample(c(TRUE, FALSE), n, replace = T),
  x4 = sample(c(TRUE, FALSE), n, replace = T),
  x5 = sample(c(TRUE, FALSE), n, replace = T),
  x6 = sample(c(TRUE, FALSE), n, replace = T)
)

> head(df)
        date value    x1    x2    x3    x4    x5    x6
1 1999-01-01     1  TRUE FALSE  TRUE  TRUE  TRUE FALSE
2 1999-01-02     3 FALSE  TRUE FALSE  TRUE FALSE FALSE
3 1999-01-03     2 FALSE FALSE  TRUE  TRUE  TRUE  TRUE
4 1999-01-04     4 FALSE FALSE  TRUE  TRUE FALSE FALSE
5 1999-01-05     4  TRUE  TRUE  TRUE  TRUE FALSE  TRUE
6 1999-01-06     0 FALSE  TRUE FALSE FALSE  TRUE FALSE
set.seed(123)
n=200
测向头(df)
日期值x1 x2 x3 x4 x5 x6
1 1999-01-01 1对错对错
2 1999-01-02 3假-真-假
3 1999-01-03 2假-假-真-真
4 1999-01-04 4假-假-真-假
5 1999-01-05 4对错
6 1999-01-06 0假真假假