Search code examples
rggplot2dplyr

How do I plot two geom_textlines + one geom_bar in a single ggplot?


I'm attempting a plot involving two geom_textlines plus a geom_bar. I think my problem has to do with telling ggplot where to use which parts of the df. The closest I've come is filtering longdf to make the geom_textline plot work, but that prevents plotting the geom_bar (I think) by preventing filter(vars == "New Wins"). As you can see, I'm trying to complete the task using dplyr.

Thanks in advance for guidance and correction!

library(dplyr)
library(tidyverse)
library(geomtextpath)

dummydf <- data.frame(vars=c('Roster','Alumni', 'New Wins'),SP22=c(34,5,4),
FA22=c(31,5,7), SP23=c(31,5,4), FA23=c(37,3,15),SP24=c(29,7,3),FA24=c(NA,NA,11))

longdf <- dummydf %>% pivot_longer(cols=c('SP22','FA22','SP23','FA23','SP24','FA24'),
names_to='semesters', values_to='value')
myplot <-longdf %>%
  filter(vars != "New Wins") %>%
  ggplot(aes(x=semesters, y=value, group=vars, color=vars)) + 
  geom_textline(aes(label = vars, hjust = vars), spacing = 100) +
  scale_hjust_manual(values = c(0.1, 0.6)) +
  scale_y_continuous(n.breaks = 16, limits = c(0, 44)) +
  scale_x_discrete(limit = c('SP22','FA22','SP23','FA23','SP24'), expand = c(0,.2)) +
  scale_color_manual(values = c("darkorchid2", "steelblue"), guide = "none") %>%
#filter(vars == "New Wins") %>%
  ggplot(aes(x=semesters, y=value, color=vars)) + 
geom_bar(aes(x = semesters, fill = 'gold1')) 
myplot


Solution

  • Maybe like this? x=semesters is the only variable mapping common to both geoms, so it might be simplest to define only that one in the global aes(). Then we can specify a custom data = ... for the geom_col layer.

    longdf %>%
      filter(vars != "New Wins") %>%
      ggplot(aes(x=semesters)) + 
      geom_col(aes(y= value), fill = 'gold1',
               data = longdf %>% filter(vars == "New Wins")) +
      geom_textline(aes(y=value, group=vars, color=vars,
                        label = vars, hjust = vars), spacing = 100) +
      scale_hjust_manual(values = c(0.1, 0.6)) +
      scale_y_continuous(n.breaks = 16, limits = c(0, 44)) +
      scale_x_discrete(limit = c('SP22','FA22','SP23','FA23','SP24'), expand = c(0,.2)) +
      scale_color_manual(values = c("darkorchid2", "steelblue"), guide = "none") 
    

    enter image description here