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\", \"
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)