2018-11-15

A simple example: Fisher's Iris


head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa

The basic graphics system

Functions create graphics, example with Fisher's Iris:

hist(iris$Petal.Length, col = "grey", border = "white",
     main = "Example of a histogram", xlab = "Fisher's Iris: petal length")

ggplot2: treating graphics as objects

Functions create a graphical object:

my_plot <- ggplot(iris) + geom_histogram(aes(Petal.Length)) +
  labs(title = "Example of a histogram",
       x = "Fisher's Iris: petal length")
my_plot

A grammar for graphics

ggplot2 builds graphics one component at a time. The grammar includes:

  • ggplot(): to provide the data
  • geom_...: to define the type of graph
  • aes(): to map features of data into aesthetic properties (e.g. shapes, colors)
my_plot <- ggplot(iris) + # use 'iris' data.frame
  geom_histogram(aes(Petal.Length)) + # hist using petal length
  labs(title = "Example of a histogram", # add title
       x = "Fisher's Iris: petal length") # add x label

Making customisation easy

For instance, to color histograms by species:

my_plot + aes(fill = Species)

Making customisation easy: scatterplot

my_plot <- ggplot(iris, aes(x = Petal.Length, y = Sepal.Length)) +
  geom_point(aes(color = Species, shape = Species),
             size = 5, alpha = .75) +
  geom_smooth() +
  labs(title = "Example of a scatterplot")
my_plot

Going further

Useful tips: specifying your colors

  • select your favourite colors, e.g. using a color picker
  • make a named vector storing these colors as character
  • specify your colors using e.g.:
col <- c(setosa = "#666699", versicolor = "#99cc00", virginica = "#b30059")
my_plot + scale_color_manual(values = col)

Note that you will need to use scale_fill_manual for colors specified through fill = ....

Useful tips: using panels

You can use facet_grid(rows ~ columns) to specify panels:

new_plot <- ggplot(iris) +
  geom_histogram(aes(x = Petal.Length, fill = Species)) +
  scale_fill_manual(values = col) + facet_grid(Species ~  .)
new_plot

Useful tips: moving the legend

Use theme(legend.position = c(x_coord, y_coord)) to move the legend:

new_plot + theme(legend.position = c(.9, .8))

Useful tips: changing the theme

Other themes are available and can be customised:

new_plot + theme_light(base_family = "Times", base_size = 20)