Variation
Visualizing Distributions
#bar Chart
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut))

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

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

Typical Values
diamonds %>%
#filter out diamonds > 3 carats
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() +
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 or values outside the scale range
## (`geom_point()`).

Covariations
#freqpoly
ggplot(data = diamonds, mapping = aes(x = price)) +
geom_freqpoly(mapping = aes(colour = cut), binwidth = 500)

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

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

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

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

ggplot(data = smaller, 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)
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()
