rsankey-diagram

Adding titles in Sankey Diagram in R


I am trying to make a Sankey chart. Below you can see my code and my data:

library(dplyr)
library(sfo)

sfo_passengers %>%
  filter(activity_period == max(activity_period)) %>%
  group_by(activity_type_code, geo_region) %>%
  summarise(total = sum(passenger_count), .groups = "drop")

sfo_passengers %>% 
  filter(operating_airline == "United Airlines",
         activity_period >= 201901 & activity_period < 202001) %>%
  mutate(terminal = ifelse(terminal == "International", "international", terminal)) %>%
  group_by(operating_airline,activity_type_code, geo_summary, geo_region,  terminal) %>%
  summarise(total = sum(passenger_count), .groups = "drop") %>%
  sankey_ly(cat_cols = c("operating_airline", "terminal","geo_summary", "geo_region", "activity_type_code"), 
            num_col = "total",
            title = "Dist. of United Airlines Passengers at SFO During 2019")

This code produces a chart without titles. Now, I want to add titles circled with a yellow color. Can anyone help me with how to do that? enter image description here


Solution

  • As the sankey_ly() function uses plotly to create plot, let's use last_plot() and add_annotations() functions to grab and enhance the plot, like:

    library(sfo)
    
    sfo_passengers %>%
      filter(activity_period == max(activity_period)) %>%
      group_by(activity_type_code, geo_region) %>%
      summarise(total = sum(passenger_count), .groups = "drop")
    
    sfo_passengers %>% 
      filter(operating_airline == "United Airlines",
             activity_period >= 201901 & activity_period < 202001) %>%
      mutate(terminal = ifelse(terminal == "International", "international", terminal)) %>%
      group_by(operating_airline,activity_type_code, geo_summary, geo_region,  terminal) %>%
      summarise(total = sum(passenger_count), .groups = "drop") %>%
      sankey_ly(cat_cols = c("operating_airline", "terminal","geo_summary", "geo_region", "activity_type_code"), 
                num_col = "total",
                title = "Dist. of United Airlines Passengers at SFO During 2019")
    
    p <- plotly::last_plot()
    
    plotly::add_annotations(p, c("Terminals", "Domestic/Int"), x = c(0.2, 0.5), y = c(1, 1), showarrow = FALSE)