bar graph: both stacked and non stacked at the same time?

Viewed 23

I have two surveys for the same population, and am looking at the impact of treatment on outcome. In survey 1, they have been exposed to either 1 or 0 treatments; in survey 2, they have been exposed to 0 - 3 treatments. I want the 1-3 treatment bars to be both spread out as the yes/no colors, and stacked in an outline, like this (I do not need the little count boxes in the upper right):

enter image description here

Which allows a comparison of any treatment (yes/no), and treatment as discrete

What I have managed thus far is this (sorry, used a slightly different sample of the data for the example above and below, but same general code applies):

enter image description here

Using the following command and sample data. Can I make the data both stacked and unstacked in a bar graph?

ggplot(sample, aes(factor(treatment), fill = factor(outcome))) +
  geom_bar(position = position_dodge2(width = 0.9, preserve = "single")) +
  facet_wrap(facets = vars(survey), labeller = as_labeller(c('1' = "Survey 1", '2' = "Survey 2"))) +
  theme(legend.position="top") +
  theme(plot.title = element_text(hjust = 0.5)) +
  coord_cartesian(ylim=c(0,30)) +
  scale_fill_discrete(labels=c("No", "Yes", "No Response")) +
  labs(title = "Interestes in outcome?", 
       fill = "",
       x = "Treatment Exposure",
       y = "Count"
  )

dput(sample)
structure(list(treatment = c(0, 0, 0, 0, 0, 0, 1, 3, 1, 2, 1, 
2, 0, 3, 0, 0, 1, 3, 0, 1, 0, 3, 0, 0, 0, 1, 1, 3, 0, 3, 0, 0, 
0, 0, 1, 2, NA, 0, 1, 3, 1, 0, 0, 1, 1, 0, 0, 0, 0, 2, 0, 0, 
1, 3, 1, 1, 0, 0, 1, 3, 0, 0, 0, 1, 1, 2, 0, 3, 1, 0, 1, 3, 1, 
0, 1, 3, 0, 0, 1, 2, 0, NA, 0, 2, 1, NA, 0, 0, 0, 1, 0, 2, 1, 
3, 1, 3, 1, 0, 1, 3, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 
0, 1, 0, NA, 1, 2, 1, 1, 0, 0, 1, 2, 1, 2, 0, 0, 1, 1, 0, 0), 
    outcome = c(1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 
    1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 
    1, 1, NA, 1, 1, 1, 1, 1, 1, 1, NA, 1, 1, 1, 1, 1, 1, 1, 1, 
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 
    1, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, 1, 1, 1, 1, 
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 
    0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 
    1, 1, 1, 1, 1, 0), survey = c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 
    2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 
    1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 
    2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 
    1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 
    2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 
    1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 
    2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 
    1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 
    2L, 1L, 2L, 1L, 2L, 1L, 2L)), row.names = c(NA, -134L), class = c("tbl_df", 
"tbl", "data.frame"))
0 Answers
Related