1

I am trying to make a bar chart in which I separate a variable using two other variables using fill in ggplot2. However, it does not allow me to use fill twice so at the moment I have used alpha but it does not look good.

Is there a way I can use fill twice? Or another aesthetic parameter I can use instead of alpha to get a better-looking graph.

My code is:

ggplot(data = s1, aes(x = Income, y = count2,
                      fill = Mental_Health_Prob,
                      alpha = Smoked_Regularly)) +
    geom_bar(stat = 'identity', position = 'dodge')

And it gives me this graph: graph

Andrea M
  • 2,314
  • 1
  • 9
  • 27
mf21
  • 11
  • 1

1 Answers1

1

I would create a new variable that contains the possible combinations of your two binary variables (easy with forcats::fct_cross()) and then pass that to the fill argument.

library(ggplot2)
library(dplyr)
library(forcats)

# Create minimal reproducible example data
s1 <- data.frame(Income = c("low", "middle", "high"),
                 Mental_Health_Prob = rep(c("Yes", "No"), each = 6),
                 Smoked_Regularly = rep(c("Yes", "No", "Yes", "No"), each = 3),
                 count2 = c(350, 220, 100, 345, 123, 564, 315, 374, 174, 534, 362, 432))

# Plot
s1 |>
    mutate(MH_smok = fct_cross(Mental_Health_Prob, Smoked_Regularly, sep = "_")) |>
    ggplot(aes(x = Income, y = count2, fill = MH_smok)) +
    geom_bar(stat = 'identity', position = 'dodge')

Created on 2022-07-09 by the reprex package (v2.0.1)

You will want to give the variable and its levels more meaningful descriptions.

Andrea M
  • 2,314
  • 1
  • 9
  • 27