2017-10-11 142 views
0

我与日期的列中,值的列和半打布尔列的数据帧ggplot方面:多布尔列

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

回答

1

听起来像您可能希望将数据帧从宽转换为长格式,并将所有布尔列收集到一个列中。例如:使用

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) 

plot

的样本数据:

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 
+0

完美!奇迹般有效。谢谢 – user2969402