library(completejourney)
## Welcome to the completejourney package! Learn more about these data
## sets at http://bit.ly/completejourney.
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(scales)
## 
## Attaching package: 'scales'
## 
## The following object is masked from 'package:purrr':
## 
##     discard
## 
## The following object is masked from 'package:readr':
## 
##     col_factor
demographics <- completejourney::demographics
transactions <- completejourney::transactions_sample
demographics %>%
  ggplot(aes(x = age, y = income, color = marital_status)) + 
  geom_jitter(alpha = .6, width = .5, height = .5, stroke = .5) + 
  scale_color_manual(values = c("pink", "lightblue", "lightgreen")) + 
  labs(title = "Age vs Income Comparison by Marital Staus", x = "Age", y = "Income")

demographics %>%
  mutate(income_num = case_when(
    income == "Under 15K" ~ 15000,
    income == "15-24K" ~ 20000, 
    income == "25-34K" ~ 30000, 
    income == "35-49K" ~ 42500, 
    income == "50-74K" ~ 62000,
    income == "75-99K" ~ 87000, 
    income == "100-124K" ~ 112000,
    income == "125-149K" ~ 137000,
    income == "150-174K" ~ 162000,
    income == "175-199K" ~ 187000,
    income == "250K+" ~ 260000, 
    TRUE ~ NA_real_
  )) %>%
  ggplot(aes(x = factor(kids_count), y = income_num)) + 
  geom_boxplot(fill = "lightblue", color = "navy") +
  scale_y_continuous(labels = comma, limits = c(0, 300000)) + 
  labs(
    title = "Income Distribution by Kids Count",
    x = "Number of Kids",
    y = "Income"
  ) 
## Warning: Removed 5 rows containing non-finite outside the scale range
## (`stat_boxplot()`).

transactions_summary <- transactions %>%
  left_join(demographics, by = "household_id") %>%
  group_by(income, household_size) %>%
  summarize(avg_sales = mean(sales_value, na.rm = TRUE), 
            avg_quantity = mean(quantity, na.rm = TRUE), 
            .groups = 'drop')

transactions_summary <- transactions_summary %>%
  mutate(income = factor(str_replace_all(income, "\\$,","")))

transactions_summary %>% 
  ggplot(aes(x = income, y = avg_sales, fill = household_size)) + 
  geom_bar(stat = "identity", position = "dodge") + 
  labs(title = "Average Sales Value by Income and Household Size",
       x = "Income", 
       y = "Average Sales Value", 
       fill = "Household Size") + 
  scale_fill_brewer(palette = "Pastel2")