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)

smaller <- diamonds %>% 
  filter(carat < 3)
  
ggplot(data = smaller, mapping = aes(x = carat)) +
  geom_histogram(binwidth = 0.1)

ggplot(data = smaller, mapping = aes(x = carat, colour = cut)) +
  geom_freqpoly(binwidth = 0.1)

Typical values

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

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

ggplot(data = smaller, mapping = aes(x = carat)) +
  geom_histogram(binwidth = 0.01)

ggplot(data = faithful, mapping = aes(x = eruptions)) + 
  geom_histogram(binwidth = 0.25)

Unusual values

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

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

Missing values

diamonds %>%
    
    # filter(y < 3 | y > 20) %>%
    
    mutate(y = ifelse(y < 3 | y > 20, NA, y)) %>%
    
    # Plot
    ggplot(aes(x = x, y = y)) +
    geom_point()
## Warning: Removed 9 rows containing missing values or values outside the scale range
## (`geom_point()`).

ggplot(data = diamonds, mapping = aes(x = x, y = y)) + 
  geom_point(na.rm = TRUE)

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 (Starting here, I no longer felt it necessary to use the textbook code chunks not discussed in the module videos after reading)

A categorial and continuous variable

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

Two catagorial variables

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

Two countinous variables

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)))
## Warning: Orientation is not uniquely specified when both the x and y aesthetics are
## continuous. Picking default orientation 'x'.

Patterns and models

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