``````# 09 Graphics for Statistical Analysis: R code
# Jerzy Wieczorek
# 9/29/15
# 36-721 Statistical Graphics and Visualization

# Set working directory

library(RColorBrewer)
library(ggplot2)
library(MASS) # for eqscplot
library(aplpack) # for bagplot
library(Hmisc) # for errbar
library(lattice) # for ethanol dataset

#### PLOTTING MATHEMATICAL FUNCTIONS ####

# curve()
curve(x^2, from = -3, to = 3)``````

``curve(sin(x), -pi, pi)``

``````# Use curve() to plot continuous PDFs and CDFs
curve(dnorm(x), -3, 3, main = "Standard Normal PDF", ylab = "Density")``````

``curve(pnorm(x), -3, 3, main = "Standard Normal CDF", ylab = "Cumulative density")``

``curve(dgamma(x, shape = 3), 0, 10, main = "Gamma(shape = 3, scale = 1) PDF", ylab = "Density")``

``curve(pgamma(x, shape = 3), 0, 10, main = "Gamma(shape = 3, scale = 1) CDF", ylab = "Cumulative density")``

``````# Contours of bivariate function:
# let's plot bivariate standard Normal PDF,
# which is just product of two independent Normal densities
x = seq(-2, 2, 0.1)
y = x
dnorm2 = function(x, y) {dnorm(x) * dnorm(y)}
z = outer(x, y, FUN = dnorm2)
contour(x, y, z)``````

``````#### DISTRIBUTIONS ####

# Load the tips dataset from
# http://www.ggobi.org/book/
# Reorder levels of day (alphabetical default is unhelpful here)
tips\$day = factor(tips\$day, levels = c("Thu", "Fri", "Sat", "Sun"))
# Attach dataset
attach(tips)

# Histograms with different bins
hist(tip, main = "Tip histogram: default bins", xlab = "Tip (\$)")``````

``````hist(tip, seq(0.5, 10.5, by = 1), xlim = c(0, 11),
main = "Tip histogram: binned to nearest \$1", xlab = "Tip (\$)")``````

``````hist(tip, seq(0.95, 10.05, by = .1), xlim = c(0, 11),
main = "Tip histogram: binned to nearest \$0.10", xlab = "Tip (\$)")``````

``````# KDEs with different bandwidths and kernels
plot(density(tip), main = "Tip KDE: default bandwidth,\nGaussian kernel", xlab = "Tip (\$)")``````

``plot(density(tip, bw = 1), main = "Tip KDE: \$1 bandwidth,\nGaussian kernel", xlab = "Tip (\$)")``

``plot(density(tip, bw = 0.1), main = "Tip KDE: \$0.10 bandwidth,\nGaussian kernel", xlab = "Tip (\$)")``