R Data Visualisation Example using R Base function

Demo dataset to be used for a plot.

# load a built in dataset e.g. iris flower dataset
head(ToothGrowth, 10)
##     len supp dose
## 1   4.2   VC  0.5
## 2  11.5   VC  0.5
## 3   7.3   VC  0.5
## 4   5.8   VC  0.5
## 5   6.4   VC  0.5
## 6  10.0   VC  0.5
## 7  11.2   VC  0.5
## 8  11.2   VC  0.5
## 9   5.2   VC  0.5
## 10  7.0   VC  0.5

Basic plots

# Box plot of one variable
boxplot(ToothGrowth$len)

Box plots by groups (dose)

# remove frame
boxplot(len ~ dose, data = ToothGrowth, frame = FALSE)

# Horizontal box plots
boxplot(len ~ dose, data = ToothGrowth, frame = FALSE,
        horizontal = TRUE)

# Notched box plots
boxplot(len ~ dose, data = ToothGrowth, frame = TRUE,
        notch = TRUE)

# Horizental Notched box plots
boxplot(len ~ dose, data = ToothGrowth, frame = TRUE,
        notch = TRUE, horizontal = TRUE)

# Change group names
boxplot(len ~ dose, data = ToothGrowth, frame = FALSE,
        names = c("D0.5", "D1", "D2")
       )

Change color in BOX plot

# Change the color of border using one single color
boxplot(len ~ dose, data = ToothGrowth, frame = FALSE,
        border = "steelblue")

# Change the color of border.
#  Use different colors for each group
boxplot(len ~ dose, data = ToothGrowth, frame = FALSE,
        border = c("#999999", "#E69F00", "#56B4E9"))

# Change fill color : single color
boxplot(len ~ dose, data = ToothGrowth, frame = FALSE,
        col = "steelblue")

# Change fill color: multiple colors
boxplot(len ~ dose, data = ToothGrowth, frame = FALSE,
        col = c("#999999", "#E69F00", "#56B4E9"))

Box plot with multiple groups

boxplot(len ~ supp * dose, data = ToothGrowth,
        col = c("white", "steelblue"), frame = FALSE)

Change main title and axis labels

# Change axis titles
# Change color (col = "gray") and remove frame

boxplot(len ~ dose, data = ToothGrowth,
        main = "Plot of length by dose",
        xlab = "Dose (mg)", ylab = "Length",
        col = "lightgray", frame = TRUE, notch = FALSE
        )
grid()