Variation

Visualizing Distributions

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

diamonds %>%
    ggplot(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(carat < 3) %>%
    ggplot(aes(x = carat)) +
    geom_histogram(binwidth = 0.01)

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

Unusual Values

ggplot(diamonds) + 
  geom_histogram(mapping = aes(x = y), binwidth = 0.5)

ggplot(diamonds) + 
  geom_histogram(mapping = aes(x = y), binwidth = 0.5) +
  coord_cartesian(ylim = c(0, 50))

Missing Values

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

Covariation

A Categorical and a Continuous Variable

ggplot(data = diamonds, mapping = aes(x = cut, y = price)) +
  geom_boxplot()

Two Categorical Variables

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

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

Two Continuous Variables

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

library(hexbin)
ggplot(data = diamonds) +
  geom_hex(mapping = aes(x = carat, y = price))

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

Patterns and Models

library(modelr)

mod <- lm(log(price) ~ log(carat), data = diamonds)

diamonds2 <- diamonds %>% 
  add_residuals(mod) %>% 
  mutate(resid = exp(resid))

ggplot(data = diamonds2) + 
  geom_point(mapping = aes(x = carat, y = resid))

ggplot(data = diamonds2) + 
  geom_boxplot(mapping = aes(x = cut, y = resid))