How to outline the bars in black in faceted graphs?

Viewed 49

I have a plot similar to Add stacked bar graphs inside faceted graphs. I want to remove the gridlines and outline each bar in black, as well as each stack.

Is there a way to do it?

library(tidyverse)
library(lubridate)
library(scales)


test <- tibble(
edu = c(rep("hs", 5), rep("bsc", 3), rep("msc", 3)),
sex = c(rep("m", 3), rep("f", 4), rep("m", 4)),
smoker = c("y", "n", "n", "y", "y", rep("n", 3), "y", "n", "n"))


test %>%
 count(sex, edu, smoker) %>%
group_by(sex) %>%
mutate(percentage = n/sum(n)) %>%
ggplot(aes(edu, percentage, fill = smoker)) +
geom_col() +
geom_text(aes(label = percent(percentage)),
 position = position_stack(vjust = 0.5)) +
facet_wrap(~sex) +
scale_y_continuous(labels = scales::percent) +
scale_fill_manual(values = c("#A0CBE8", "#F28E2B"))
2 Answers

Use theme()

You can use geom_col(color = "black") for the black outline, and theme(panel.grid = element_blank()) to remove the grid lines.

library(tidyverse)
library(lubridate)

test <- tibble(
  edu = c(rep("hs", 5), rep("bsc", 3), rep("msc", 3)),
  sex = c(rep("m", 3), rep("f", 4), rep("m", 4)),
  smoker = c("y", "n", "n", "y", "y", rep("n", 3), "y", "n", "n"))

test %>%
  count(sex, edu, smoker) %>%
  group_by(sex) %>%
  mutate(percentage = n/sum(n)) %>%
  ggplot(aes(edu, percentage, fill = smoker)) +
  geom_col(color = "black") +
  geom_text(aes(label = percent(percentage)),
            position = position_stack(vjust = 0.5)) +
  facet_wrap(~sex) +
  scale_y_continuous(labels = scales::percent) +
  scale_fill_manual(values = c("#A0CBE8", "#F28E2B")) +
  theme(panel.grid = element_blank())

Created on 2022-08-05 by the reprex package (v2.0.1)

Use theme_cowplot()

Another way to remove the grid line is to use a well established package cowplot.

library(tidyverse)
library(lubridate)
library(scales)
library(cowplot)

test %>%
  count(sex, edu, smoker) %>%
  group_by(sex) %>%
  mutate(percentage = n/sum(n)) %>%
  ggplot(aes(edu, percentage, fill = smoker)) +
  geom_col(color = "black") +
  geom_text(aes(label = percent(percentage)),
            position = position_stack(vjust = 0.5)) +
  facet_wrap(~sex) +
  scale_y_continuous(labels = scales::percent) +
  scale_fill_manual(values = c("#A0CBE8", "#F28E2B")) +
  theme_cowplot()

Created on 2022-08-05 by the reprex package (v2.0.1)

We could also use theme_classic()

test %>%
  count(sex, edu, smoker) %>%
  group_by(sex) %>%
  mutate(percentage = n/sum(n)) %>%
  ggplot(aes(edu, percentage, fill = smoker)) +
  geom_col(color="black", size=1) +
  geom_text(aes(label = percent(percentage)),
            position = position_stack(vjust = 0.5)) +
  facet_wrap(~sex) +
  scale_y_continuous(labels = scales::percent) +
  scale_fill_manual(values = c("#A0CBE8", "#F28E2B")) +
  theme_classic()

enter image description here

Related