Chapter 2. Quickly Exploring Data

library(ggplot2)
library(gcookbook)

Section 2.1. Creating a Scatter Plot

# Figure 2-1
plot(mtcars$wt, mtcars$mpg)

# Figure 2-2
qplot(wt, mpg, data=mtcars)

Section 2.2. Creating a Line Graph

# Figure 2-3
plot(pressure$temperature, pressure$pressure, type="l")

plot(pressure$temperature, pressure$pressure, type="l")
points(pressure$temperature, pressure$pressure)

lines(pressure$temperature, pressure$pressure/2, col="red")
points(pressure$temperature, pressure$pressure/2, col="red")

# Figure 2-4
qplot(pressure$temperature, pressure$pressure, geom="line")

qplot(pressure$temperature, pressure$pressure, geom=c("line", "point"))

Section 2.3. Creating a Bar Graph

# Figure 2-5
barplot(BOD$demand, names.arg=BOD$Time)

barplot(table(mtcars$cyl))

# Figure 2-6
ggplot(BOD, aes(Time, demand)) +
  geom_bar(stat="identity")

ggplot(BOD, aes(factor(Time), demand)) +
  geom_bar(stat="identity")

# Figure 2-7
qplot(mtcars$cyl)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

qplot(factor(mtcars$cyl))

Section 2.4. Using Colors in a Bar Graph

# Figure 2-8
hist(mtcars$mpg)

hist(mtcars$mpg, breaks=10)

# Figure 2-9
qplot(mtcars$mpg)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

qplot(mpg, data=mtcars, binwidth=4)

Section 2.5. Creating a Box Plot

# Figure 2-10
plot(ToothGrowth$supp, ToothGrowth$len)

boxplot(len ~ supp + dose, data = ToothGrowth)

# Figure 2-11
qplot(supp, len, data=ToothGrowth, geom="boxplot")

qplot(interaction(supp, dose), len, data=ToothGrowth, geom="boxplot")

Section 3.6. Plotting a Function Curve

# Figure 2-12
curve(x^3 - 5*x, from=-4, to=4)

myfun <- function(xvar) {
  1/(1 + exp(-xvar +10))
}
curve(myfun(x), from=0, to=20)
curve(1-myfun(x), add=TRUE, col="red")

# Figure 2-13
ggplot(data.frame(x=c(0,20)), aes(x=x)) +
  stat_function(fun=myfun, geom = "line")


END!