1 Goal


The goal of this tutorial is to learn the use of the scale_colour_manual function of ggplot. We will draw different scandinavian flags for this purpose. We will define a different colour palette for each country.


2 Scandinavian flags

2.1 Creating canvas


# First we load the libraries
library(ggplot2)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
# Let's create 200k points on a 16x10 grid
x <- runif(200000, min = 0, max = 16)
y <- runif(200000, min = 0, max = 10)

# We create the dataframe
flag <- as.data.frame(x = x)
flag$y <- y

# Now we add the colour
flag <-mutate(flag, flag_colour = ifelse(((x > 5) & (x<=7)) | ((y > 4) & (y<=6)), "cross", "bckgd"))

2.2 Denmark flag


DenmarkPalette <- c("red", "white")

ggplot(flag) + geom_point(aes(x = x, y = y, color = flag_colour), size = 0.1) + coord_fixed(ratio = 1) + scale_colour_manual(values = DenmarkPalette)


2.3 Finland flag


FinlandPalette <- c("white", "blue")

ggplot(flag) + geom_point(aes(x = x, y = y, color = flag_colour), size = 0.1) + coord_fixed(ratio = 1) + scale_colour_manual(values = FinlandPalette)


2.4 Sweden flag


SwedenPalette <- c("blue", "yellow")

ggplot(flag) + geom_point(aes(x = x, y = y, color = flag_colour), size = 0.1) + coord_fixed(ratio = 1) + scale_colour_manual(values = SwedenPalette)


3 Norway and Iceland flags

3.1 Creating the canvas


# Now we create the flag of norway
# Let's create 200k points on a 21x16 grid
x <- runif(200000, min = 0, max = 21)
y <- runif(200000, min = 0, max = 16)

flag <- as.data.frame(x = x)
flag$y <- y

# Now we add the colour, however this flags contain two crosses
flag <-mutate(flag, flag_colour = ifelse(((x > 6) & (x<=10)) | ((y > 6) & (y<=10)), "cross", "bckgd"))
crossed_flag <- flag[which(flag$flag_colour == "cross"),]
flag[which(flag$flag_colour == "cross"),] <- mutate(crossed_flag, flag_colour = ifelse(((x > 7) & (x<=9)) | ((y > 7) & (y<=9)), "inner_cross", "cross"))

3.2 Norway flag


NorwayPalette <- c("red", "white", "blue")
ggplot(flag) + geom_point(aes(x = x, y = y, color = flag_colour), size = 0.1) + coord_fixed(ratio = 1) + scale_colour_manual(values = NorwayPalette)


3.3 Iceland flag


IcelandPalette <- c("blue", "white", "red")
ggplot(flag) + geom_point(aes(x = x, y = y, color = flag_colour), size = 0.1) + coord_fixed(ratio = 1) + scale_colour_manual(values = IcelandPalette)


4 Conclusion


In this tutorial we have learnt the use of the colour palette in ggplot in scatter plots. We have used different colour configurations to draw the different flags from the scandinavian countries.