1. Plotting

Let’s learn how to plot some simple graphs.

[1]:
set.seed(37)

1.1. Box plot

Here’s an example box plot.

[2]:
x <- rnorm(1000, mean=0, sd=1)
y <- rnorm(1000, mean=5, sd=5)

options(repr.plot.width=4, repr.plot.height=4)

boxplot(x, y, names=c('x', 'y'), xlab='variables', ylab='value', col='gray90')
title('Box Plot')
_images/plot_3_0.png

We may also change the box plot to be horizontal.

[3]:
x <- rnorm(1000, mean=0, sd=1)
y <- rnorm(1000, mean=5, sd=5)

options(repr.plot.width=4, repr.plot.height=4)

boxplot(x, y, names=c('x', 'y'), xlab='variables', ylab='value', col='gray90', horizontal=TRUE)
title('Box Plot')
_images/plot_5_0.png

1.2. Scatter plot

[4]:
x <- rnorm(300, mean=0, sd=1)
y <- rnorm(300, mean=5, sd=5)

options(repr.plot.width=4, repr.plot.height=4)

plot(x, y, pch=3)
abline(lm(y ~ x), lty='dotted', lwd=2, col='red')
title('Scatter Plot')
_images/plot_7_0.png

1.3. Pairs plot

The pairs plot shows multiple scatter plots on one graphic.

[5]:
x <- rnorm(300, mean=0, sd=1)
y <- rnorm(300, mean=1.5, sd=2.0)
z <- 5 + 3 * x - 2 * y + rnorm(300, mean=0, sd=1)

data <- data.frame(
    x = x,
    y = y,
    z = z
)

options(repr.plot.width=5, repr.plot.height=5)

pairs(data)
_images/plot_9_0.png

1.4. Line plot

[6]:
t <- seq(1:100)
s <- sin(t) + rnorm(100, mean=1, sd=1)

options(repr.plot.width=10, repr.plot.height=5)

plot(t, s, type='l')
_images/plot_11_0.png

1.5. Pie charts

[7]:
e <- c(100, 50, 200)
l <- c('business', 'social', 'military')
c <- c('gray40', 'gray50', 'gray90')

options(repr.plot.width=4, repr.plot.height=4)

pie(e, labels=l, col=c)
_images/plot_13_0.png

1.6. Dot charts

[8]:
e <- c(100, 50, 200)
l <- c('business', 'social', 'military')

options(repr.plot.width=4, repr.plot.height=4)

dotchart(e, labels=l)
_images/plot_15_0.png

1.7. Bar chart

[9]:
e <- c(100, 50, 200)
l <- c('business', 'social', 'military')

options(repr.plot.width=4, repr.plot.height=4)

barplot(e, names=l)
_images/plot_17_0.png