# Load package
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.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ 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

Introduction

Questions

Variation

Visualizing distributions

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

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 bigger diamonds
    filter(carat < 3) %>%
    
    # plot
    ggplot(aes(carat)) +
    geom_histogram(binwidth = 0.1)

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

Unusual values

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

diamonds %>%
    ggplot(aes(x = 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(aes(x = x, y = y)) +
    geom_point()
## Warning: Removed 9 rows containing missing values (`geom_point()`).

## Covariation

a categorical and continous 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 continous variables

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

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

Patterns and Models

library(modelr)

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

diamonds2 <- diamonds %>%
    modelr::add_residuals(mod) %>%
    mutate(resid = exp(resid))
diamonds2 %>%
    ggplot(aes(carat,resid)) +
    geom_point()