1

I have this small subset of a larger data frame:

years  <- c(2015, 2019, 2020, 2021, 2021, 2022)
Points <- c(7, 26, 9, 18, 28, 12)
Design <- c("Standard 2019", "Standard 2019", "Standard 2019", "Standard 2019", "LCT 2021", "LCT 2021")
PointSummary <- data.frame(years, Points, Design)

I want to create a stacked bar plot showing the number of points sampled in each year and in each design (Standard 2019 or LCT 2021). It should look like this:

desired stacked bar plot

I can change the themes and such myself, but I need help adding labels to the stacked bars. Here is my current code, calling geom_text:

library(ggplot2)
ggplot(data = PointSummary, aes(x = years, y = Points, fill = Design)) +
  geom_bar() +
  geom_text(position = position_stack(vjust = 1.6), color = "white", size = 6)
Mikael Jagan
  • 9,012
  • 2
  • 17
  • 48
DrewB31
  • 11
  • 1

1 Answers1

1

Something like this?

ggplot(within(PointSummary, years <- factor(years, c(2015, "", 2019:2022))),
       aes(x = years, y = as.numeric(as.character(Points)), fill = Design)) +
  geom_col(position = position_stack()) +
  geom_text(aes(label = Points), position = position_stack(vjust = 0.5),
            color="white", size = 6) +
  scale_x_discrete(drop = FALSE) +
  scale_fill_manual(values = c("gray70", "gray30")) +
  labs(y = "Points") +
  theme_classic(base_size = 20)

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • Allan, thank you for your help! Definitely a different direction than I was taking when trying to figure this out. Now to digest just how that code works – DrewB31 Mar 16 '23 at 00:07