knitr::opts_chunk$set(echo = TRUE)

library(tidyverse)
library(lubridate)
library(completejourney)

transactions <- get_transactions()
#dim(transactions)

promotions <- get_promotions()
#dim(promotions)

df <- transactions %>% 
  inner_join(demographics, by = "household_id") %>% 
  inner_join(products, by = "product_id")
#df

Plot 1

df %>% 
  group_by(age) %>% 
  filter(sales_value < 100) %>% 
  ggplot(aes(age, sales_value, color = income)) +
  geom_jitter(width = .2) +
  stat_summary(fun = "median", geom = "point", color = "red", size = 2) +
  labs(title = "Strip Plot",
       subtitle = "Sales Values Less Than $100 by Age",
       x = "Age Group",
       y = "Sales Value",
       color = "Income",
       caption = "High Income Earners Spread Throughout Age Groups") +
  theme(plot.caption = element_text(size = 12, color = "Blue"))

Plot 2

df2 <- df %>% 
  group_by(product_id, income) %>% 
  summarise(total_sales_value = sum(sales_value), total_quantity = sum(quantity))
ggplot(df2, aes(total_quantity, total_sales_value, color = income)) +
  geom_point() +
  geom_smooth() +
  facet_wrap(~income) +
  scale_x_continuous(labels = scales::label_number_si()) +
  scale_y_continuous(labels = scales::dollar) %>% 
  labs(title = "Scatterplot Smoothed Facet Wrap",
       subtitle = "Quantity vs. Sales by Income",
       x = "Quantity",
       y = "Total Sales ($)",
       color = "Income Range",
       caption = "Middle Income Earners Spend Greatest Amount") +
  theme(plot.caption = element_text(size = 12, color = "Blue"))

Plot 3

df3 <- df %>% 
  group_by(product_category) %>% 
  summarise(total_quantity = sum(quantity), total_sales_value = sum(sales_value)) %>% 
  arrange(desc(total_sales_value)) %>% 
  slice_max(total_sales_value, n = 25)
#df3
  
df3 %>% 
  mutate(pct = total_sales_value / sum(total_sales_value)) %>% 
  ggplot(aes(pct, reorder(product_category, pct))) +
  geom_point(color = "blue") +
  scale_x_continuous(labels = scales::percent) + 
  labs(title = "Dot Plot",
       subtitle = "Product Category Percentage of Total",
       x = "Percent",
       y = "Product Category",
       caption = "Coupon / Misc Items has Greatest % of Spend for Top 25 Product Categories") +
  theme(plot.caption = element_text(size = 12, color = "Blue"))