Introduction

Questions

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 = ifelse(y < 3 | y > 20, NA, y)) %>%
    
    #Plot
    ggplot(data = diamonds, mapping = aes(x = x, y = y)) +
    geom_point()

nycflights13::flights %>% 
  mutate(
    cancelled = is.na(dep_time),
    sched_hour = sched_dep_time %/% 100,
    sched_min = sched_dep_time %% 100,
    sched_dep_time = sched_hour + sched_min / 60
  ) %>% 
  ggplot(mapping = aes(sched_dep_time)) + 
    geom_freqpoly(mapping = aes(colour = cancelled), binwidth = 1/4)

#Covariation ## Categorial and continuous variables

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

ggplot(data = mpg) +
  geom_boxplot(mapping = aes(x = reorder(class, hwy, FUN = median), y = hwy))

ggplot(data = mpg) +
  geom_boxplot(mapping = aes(x = reorder(class, hwy, FUN = median), y = hwy)) +
  coord_flip()

Two categorial variables

ggplot(data = diamonds) +
  geom_count(mapping = aes(x = cut, y = color))

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

Two continuous variables

ggplot(data = diamonds) +
  geom_point(mapping = aes(x = carat, y = price))

ggplot(data = diamonds) + 
  geom_point(mapping = aes(x = carat, y = price), alpha = 1 / 100)

library(hexbin)
diamonds %>%
    ggplot(aes(x = carat, y = price)) +
    geom_hex()

diamonds %>%
    filter(carat < 3) %>%
    ggplot(aes(x = carat, y = price)) +
    geom_boxplot(aes(group = cut_width(carat, 0.1)))

#Patterns and models

library(modelr)
library(tidyverse)
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()

diamonds %>% 
  count(cut, clarity) %>% 
  ggplot(aes(clarity, cut, fill = n)) + 
    geom_tile()