## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  cache = FALSE,
  fig.width = 7,
  fig.height = 5,
  eval = nzchar(Sys.getenv("COMPILE_VIG"))
)

## -----------------------------------------------------------------------------
library(cansim)

# select a table number
table_id = "36-10-0402"

# get table overview
get_cansim_table_overview(table_id)

## -----------------------------------------------------------------------------
library(dplyr, warn.conflicts = FALSE)

data <- get_cansim(table_id) 

selected_value = data$Prices[grepl("Chained",data$Prices)] %>% unique()
data <- data %>% 
  filter(Prices == selected_value)

## -----------------------------------------------------------------------------
# Extract top-level hierarchy to calculate total
top_level <- categories_for_level(data, "North American Industry Classification System (NAICS)",0)

# Extract total using hierarchy and calculate share by NAICS. 
# This could also be done using grouping functions from dplyr, 
# but we wanted to demonstrate how to use specific hierarchy levels. 
total_data <- data %>% 
  filter(`North American Industry Classification System (NAICS)` %in% top_level) %>% 
  rename(Total = val_norm) %>% 
  select(Date, GEO, Total)

# Merge total back in and calculate share for every NAICS code
data <- data %>% 
  left_join(total_data,by = c("Date", "GEO")) %>% 
  mutate(Share = val_norm/Total)

## -----------------------------------------------------------------------------
cut_data <- data %>% filter(
  !grepl("T\\d+",`Classification Code for North American Industry Classification System (NAICS)`),
  `North American Industry Classification System (NAICS)` %in% 
    categories_for_level(.,"North American Industry Classification System (NAICS)",1))

# How many are NAICS categories left? 
n <- length(cut_data$`North American Industry Classification System (NAICS)` %>% unique)

## ----fig.height=6, fig.width=9------------------------------------------------
# Specify which regions and period we want to look at 
regions = "British Columbia"
period = "2019-07-01"

# Select the top-8 categories for our reference region and period
top_categories <- cut_data %>% 
  filter(GEO %in% regions, Date == period) %>% 
  top_n(8,Share) %>% 
  pull("North American Industry Classification System (NAICS)")

# Group remaining categories together and prepare data for plot
plot_data <- cut_data %>% 
  mutate(NAICS = ifelse(`North American Industry Classification System (NAICS)` %in% top_categories,`North American Industry Classification System (NAICS)`,"Rest")) %>%
  select(Date, GEO, NAICS, VALUE, Share) %>%
  group_by(Date, GEO, NAICS) %>%
  summarise(VALUE = sum(VALUE, na.rm = TRUE),
            Share = sum(Share, na.rm = TRUE),
            .groups = "drop") 

## ----fig.height=6, fig.width=9, fig.alt="Vignette example plot, GDP by NAICS"----
library(ggplot2)

ggplot(plot_data %>%  filter(GEO %in% regions), 
       aes(x = Date, y = Share, fill = NAICS)) +
  geom_area(position="stack") +
  scale_y_continuous(labels = scales::percent) +
  theme_bw() +
  theme(legend.position = "bottom",legend.direction ="vertical") +
  guides(fill=guide_legend(ncol = 3)) +
  labs(title="Gross domestic product (GDP) at basic prices",
       subtitle=selected_value,
       x="", fill = "", 
       caption=paste0("CANSIM ", table_id))


## ----fig.height=10, fig.width=9, warning=FALSE, fig.alt="Vignette example plot, GDP by NAICS"----
real_construction <- c("Construction [23]","Real estate and rental and leasing [53]")

# Get the NAICS hierarchy codes just for these categories
rrl_hierarchy <- data %>% 
  filter(`North American Industry Classification System (NAICS)` %in% real_construction) %>% 
  pull("Hierarchy for North American Industry Classification System (NAICS)") %>% 
  unique

# Filter out all sub-categories for Real Estate. 
# The paste with | trick ensures that we grepl for all matches. 
rrl_data <- data %>% 
  filter(grepl(paste(rrl_hierarchy,collapse="|"),`Hierarchy for North American Industry Classification System (NAICS)`))

# Ensure we only retain the NAICS leaves and none of the aggregate subcategories
rrl_data <- rrl_data %>% 
  filter(
  `North American Industry Classification System (NAICS)` %in% 
    categories_for_level(.,"North American Industry Classification System (NAICS)")) %>%
  rename(NAICS=`North American Industry Classification System (NAICS)`)

# Plot with labels from our original selections
ggplot(rrl_data %>% filter(GEO %in% regions),
       aes(x = Date, y = Share, fill = NAICS)) +
  geom_area(position = "stack") +
  scale_y_continuous(labels = scales::percent) +
  theme_bw() +
  theme(legend.position = "bottom",legend.direction ="vertical") +
  guides(fill=guide_legend(ncol=1)) +
  labs(title="Gross domestic product (GDP) at basic prices",
       subtitle=paste0(regions,", ", selected_value),
       x="",
       caption=paste0("CANSIM ", table_id))

