Introduction
Question
Variation
Visualizing Distribution
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut))

ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat), 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
ggplot(data = smaller, mapping = aes(x = carat)) +
geom_histogram(binwidth = 0.01)

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

Unusual values
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))%>%
#plot
ggplot(aes(x = x, y = y))+
geom_point()
## Warning: Removed 9 rows containing missing values or values outside the scale range
## (`geom_point()`).

Covariation
A categorical and continuous variable
diamonds %>%
ggplot(aes(x = cut, y = price))+
geom_boxplot()

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

two continuous variables
ggplot(data = smaller) +
geom_bin2d(mapping = aes(x = carat, y = price))
## `stat_bin2d()` using `bins = 30`. Pick better value `binwidth`.

ggplot(data = smaller) +
geom_hex(mapping = aes(x = carat, y = price))

ggplot(data = smaller, mapping = aes(x = carat, y = price)) +
geom_boxplot(mapping = 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)
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))
