0

Using ggplot2 I am trying to create a grouped AND stacked barchart without using faceting. I want to avoid faceting, because I need to facet on years once I have a grouped and stacked barchart for the variables provided in the example.

This is the best solution so far:

df <- data.frame("industry"=c("A","A", "B", "B", "C", "C",
                              "A","A", "B", "B", "C", "C"), 
                 "value"=c(4,6,7,1, 5,9,8,3, 5,5,6,7),
                 "woman"=c(1,0,1,0,1,0,1,0,1,0,1,0),
                 "disabled"=c(1,1,1,1,1,1,0,0,0,0,0,0))

ggplot(df,aes(paste(industry,disabled),value))+
  geom_col(aes(fill=factor(woman)))+
  coord_flip()

enter image description here

This is basically what I want (see link above), but the bars should be grouped within each industry, using just one label for industry for both values of disabled. No label needed for disabled. The disabled=0 bars should have a faded color compared to the disabled=1 bars.

The intention of the chart is to display the distribution of employment across industries for the disabled population, compared to the general population (faded) and to show gender proportions for each population. (Values in example just for illustration).

markus
  • 25,843
  • 5
  • 39
  • 58
Jannike
  • 13
  • 2

1 Answers1

0

Try this:

library(ggplot2)

ggplot(df, aes(interaction(disabled, industry), value, alpha = factor(woman))) +
  geom_col(aes(fill = factor(woman))) +
  scale_alpha_manual(values = c(0.5, 1)) +
  scale_x_discrete(labels = c(0, 1, 0, 1, 0, 1)) +
  annotate("text", label = "A", x = 1.5, y = -2) +
  annotate("text", label = "B", x = 3.5, y = -2) +
  annotate("text", label = "C", x = 5.5, y = -2) +
  coord_cartesian(ylim = c(0, 15), clip = "off", expand = FALSE) +
  coord_flip(ylim = c(0, 15), clip = "off", expand = TRUE) +
  theme(axis.title.y = element_blank())

We are manually specifying that alpha values should vary by factor(woman) and setting the level-specific alpha values using scale_alpha_manual(). We set your subgroup 0,1 labels manually with scale_x_discrete. We are using annotate() to place your group labels, which can be placed outside of the plotting area by using coord_cartesian() with clip = "off".

Raoul Duke
  • 435
  • 3
  • 13
  • Thank you so much Raoul! This helped me a lot. I was able to use your code and modify it slightly so that I get what I want. For example, I want alpha to vary by disabled, not woman. Now I just need to add som space between every other bar, so that the As and Bs and Cs are visually clustered. Is there a way to do that? – Jannike May 02 '19 at 18:56
  • Glad to help. To answer your second question, I would play around with `geom_col(aes(fill = factor(woman)), position = position_dodge(width = 0.8), width = 0.6)`. https://stackoverflow.com/questions/6085238/adding-space-between-bars-in-ggplot2 and related questions. – Raoul Duke May 02 '19 at 19:18