01 Aesthetic mappings


Plots map data onto graphical elements

Dataset:

Daily hours between sunrise and sunset for various locations in 2022

Sunrise and sunset time
City Date Hours between sunrise and sunset month
Cape Town, South Africa 2022-01-01 14.55000 Jan
Cape Town, South Africa 2022-01-02 14.53333 Jan
Cape Town, South Africa 2022-01-03 14.53333 Jan
Cape Town, South Africa 2022-01-04 14.51667 Jan
Cape Town, South Africa 2022-01-05 14.50000 Jan
Cape Town, South Africa 2022-01-06 14.48333 Jan
Cape Town, South Africa 2022-01-07 14.46667 Jan
Cape Town, South Africa 2022-01-08 14.45000 Jan
Cape Town, South Africa 2022-01-09 14.43333 Jan
Cape Town, South Africa 2022-01-10 14.41667 Jan
Source: Schools observatory

Sun hours mapped onto y position

Sun hours mapped onto colour

Creating aesthetic mappings in ggplot

We define the mapping with aes()

ggplot(
  data = sun_hours,
  mapping = aes(x = date, y = sun_hours, colour = city)
) + geom_line(size = 2)

We define the mapping with aes()

ggplot(
  data = sun_hours,
  mapping = aes(x = date, y = city, colour = sun_hours)
) + geom_point(size = 5)

We frequently omit argument names


Long form, all arguments are named:

ggplot(
  data = sun_hours,
  mapping = aes(x = date, y = city, colour = sun_hours)
) + geom_point(size = 5)


Abbreviated form, common arguments remain unnamed:

ggplot(sun_hours, aes(date, city, colour = sun_hours)) + 
  geom_point(size = 5)

The geom determines how the data is shown

ggplot(sun_hours, aes(date, sun_hours, colour = city)) + 
  geom_line(size = 2)

The geom determines how the data is shown

ggplot(sun_hours, aes(date, city, colour = sun_hours)) + 
  geom_point(size = 5)

The geom determines how the data is shown

ggplot(sun_hours, aes(month, sun_hours, colour = city)) + 
  geom_boxplot()

The geom determines how the data is shown

ggplot(sun_hours, aes(month, sun_hours, fill = city)) + 
  geom_violin() +
  facet_wrap(vars(city))

Important: colour and fill apply to different elements

colour and fill apply to different elements

  • colour applies colour to points, lines, text, borders

  • fill applies colour to any filled areas

Many geoms have both colour and fill aesthetics

ggplot(sun_hours, aes(month, sun_hours, colour = city)) + 
  geom_boxplot()

Many geoms have both colour and fill aesthetics

ggplot(sun_hours, aes(month, sun_hours, fill = city)) + 
  geom_boxplot()

Many geoms have both colour and fill aesthetics

ggplot(sun_hours, aes(month, sun_hours, colour = city, fill = city)) + 
  geom_boxplot()

Aesthetics can also be used as parameters in geoms

ggplot(sun_hours, aes(month, sun_hours, fill = city)) + 
  geom_boxplot(colour = "midnightblue")

Aesthetics can also be used as parameters in geoms

ggplot(sun_hours, aes(month, sun_hours, colour = city)) + 
  geom_boxplot(fill = "midnightblue")

Further reading