Introduction

Questions

# 1) What type of variation occurs within my variable?

# 2) What type of covariation occurs between my variables? 

Variation

Visualizing Distributions

diamonds %>%
    ggplot(aes(x = cut)) + 
    geom_bar()

diamonds %>%
ggplot(mapping = aes(x = carat)) + 
    geom_histogram(binwidth = 0.5)

diamonds %>%
    filter(carat < 3) %>% 
    
    ggplot(aes(x = carat)) + 
    geom_histogram(binwidth = 0.5)

diamonds %>%
    ggplot(aes(x = carat, color = cut)) + 
    geom_freqpoly()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Typical Values

diamonds %>%
    
    # Filter out diamonds > 3 carat
    filter(carat < 3) %>%
    
    # Plot
    ggplot(aes(x = carat)) +
    geom_histogram(binwidth = 0.01) 

faithful %>%
    ggplot(aes(eruptions)) + 
    geom_histogram(binwidth = 0.25)

Unusual Values

diamonds %>%
    ggplot(aes(y)) +
    geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

diamonds %>%
    ggplot(aes(y)) +
    geom_histogram() + 
    coord_cartesian(ylim = c(0, 50))
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Missing Values

diamonds %>%
    
    # filter (y > 3 | y > 20) %>%
    
    mutate(y_rev = ifelse(y > 3 | y > 20, NA, y)) %>%
    
    # Plot
    ggplot(aes(x = x, y = y)) +
    geom_point()

Covariation

A categorical and continuous variable

diamonds %>%
    ggplot(aes(x = cut, y = price)) +
    geom_boxplot()

Two categorical variables

diamonds %>%
    
    count (color, cut) %>%
    
    ggplot(aes(x = color, y = cut, fill = n)) + 
    geom_tile()

Two continuous variables

library(hexbin)
## Warning: package 'hexbin' was built under R version 4.4.3
diamonds %>% 
    ggplot(aes(x = carat, y = price)) + 
    geom_hex()

diamonds %>%
    filter(carat < 3) %>%
    ggplot(aes(carat = x, y = price)) + 
    geom_boxplot(aes(group = cut_width(carat, 0.1)))
## Warning: The following aesthetics were dropped during statistical transformation: carat.
## ℹ This can happen when ggplot fails to infer the correct grouping structure in
##   the data.
## ℹ Did you forget to specify a `group` aesthetic or to convert a numerical
##   variable into a factor?

Patterns and Models

library(modelr)
## Warning: package 'modelr' was built under R version 4.4.3
mod <- lm(log(price) ~ log (carat), data = diamonds)

diamonds4 <- diamonds %>%
    modelr::add_residuals(mod) %>%
    mutate(resid = exp(resid))

diamonds4 %>%
    ggplot(aes(carat, resid)) + 
    geom_point()

diamonds4 %>% 
    ggplot(aes(cut, resid)) + 
    geom_boxplot()