rm(list = ls()) # clean-up workspace
library("tidyverse")
## ── Attaching packages ───────────────────────────────────────────────────────────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.2     ✓ purrr   0.3.4
## ✓ tibble  3.0.3     ✓ dplyr   1.0.2
## ✓ tidyr   1.1.2     ✓ stringr 1.4.0
## ✓ readr   1.3.1     ✓ forcats 0.5.0
## ── Conflicts ──────────────────────────────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()

Some more exercise on ggplot2

embed a plot inside another

In this part, we want to replicate the plots in reference.

  1. create the data and do the initial visualization
set.seed(42)
n <- 1000
x <- runif(n) * 3
y <- x * sin(1/x) + rnorm(n) / 25
df <- tibble(x = x, y = y)
p1 <- ggplot(df, aes(x, y)) +
  geom_point(alpha = 0.3) +
  geom_smooth(se = FALSE) +
  theme_bw()
p1
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

Let’s further take a look over the function \(f(x) = x \sin(\frac{1}{x})\).

Create a new variable \(z\) to store the \(f(x)\) values at each \(x\) point.

df.with.z <- df %>%
  add_column(z = x * sin(1 / x))

Now plot another figure with two layers:

  • Scatter plot of the points (x, y)

  • A line by (x, z)

Put your code inside the code block, explain your findings outside the code block (so that it renders to text in the HTML file).

You may want to change eval = TRUE or remove it for the code to be executed.

p2

Now we see that the default smoothing function doesn’t catch the beginning part of these points.

Let’s zoom in (with clipping) the region \(x \in [0, 0.5]\) and make another plot.

p3

Now embed p3 inside p1.

Please add appropriate titles and subtitles to them.

p1 + annotation_custom(ggplotGrob(p3), xmin = 1, xmax = 3, ymin = -0.3, ymax = 0.6)

Now please follow the second half of the reference, but instead create a UK map similar to this one and save it as uk_map.pdf

Hint: it’s time to practice your self-learning (google?) skills.


Target UK map


A bad map your instructor created.

# Your code for the UK map