ggplot geom_bar where x = multiple columns

后端 未结 4 1162
情深已故
情深已故 2020-12-07 03:21

How can I go about making a bar plot where the X comes from multiple values of a data frame?

Fake data:

data <- data.frame(col1 = rep(c(\"A\", \"         


        
4条回答
  •  抹茶落季
    2020-12-07 04:10

    A very rough approximation, hoping it'll spark conversation and/or give enough to start.

    Your data is too small to do much, so I'll extend it.

    set.seed(2)
    n <- 100
    d <- data.frame(
      cat1 = sample(c('A','B','C'), size=n, replace=TRUE),
      cat2 = sample(c(2012L,2013L,2014L,2015L), size=n, replace=TRUE),
      cat3 = sample(c('^','v','<','>'), size=n, replace=TRUE),
      val = sample(c('X','Y'), size=n, replace=TRUE)
    )
    

    I'm using dplyr and tidyr here to reshape the data a little:

    library(ggplot2)
    library(dplyr)
    library(tidyr)
    
    d %>%
      tidyr::gather(cattype, cat, -val) %>%
      filter(val=="Y") %>%
      head
    # Warning: attributes are not identical across measure variables; they will be dropped
    #   val cattype cat
    # 1   Y    cat1   A
    # 2   Y    cat1   A
    # 3   Y    cat1   C
    # 4   Y    cat1   C
    # 5   Y    cat1   B
    # 6   Y    cat1   C
    

    The next trick is to facet it correctly:

    d %>%
      tidyr::gather(cattype, cat, -val) %>%
      filter(val=="Y") %>%
      ggplot(aes(val, fill=cattype)) +
      geom_bar() +
      facet_wrap(~cattype+cat, nrow=1)
    

提交回复
热议问题