## 5.2 Scales

### 5.2.1 Logarithmic

p1 <- p0 + scale_x_log10()

### 5.2.2 Expand limits

Specify the value you want to be included:

p2 <- p0 + expand_limits(y = 0)

Or two:

p3 <- p0 + expand_limits(y = c(0, 100))

By default, ggplot() adds some padding around the included area (see how the scale doesn’t start from 0, but slightly before). You can remove this padding with the expand option:

p4 <- p0 +
expand_limits(y = c(0, 100)) +
coord_cartesian(expand = FALSE)

We are now using a new library - patchwork - to print all 4 plots together. Its syntax is very simple - it allows us to add ggplot objects together. (Trying to do p1 + p2 without loading the patchwork package will not work, R will say “Error: Don’t know how to add p2 to a plot”.)

library(patchwork)
p1 + p2 + p3 + p4 + plot_annotation(tag_levels = "1", tag_prefix = "p")

### 5.2.3 Zoom in

p1 <- p0 +
coord_cartesian(ylim = c(70, 85), xlim = c(20000, 40000))

### 5.2.4 Exercise

How is this one different to the previous?

p2 <- p0 +
scale_y_continuous(limits = c(70, 85)) +
scale_x_continuous(limits = c(20000, 40000))

Answer: the first one zooms in, still retaining information about the excluded points when calculating the linear regression lines. The second one removes the data (as the warnings say), calculating the linear regression lines only for the visible points.

p1 + p2
## Warning: Removed 114 rows containing non-finite values (stat_smooth).
## Warning: Removed 114 rows containing missing values (geom_point).

### 5.2.5 Axis ticks

p1 <-  p0 +
coord_cartesian(ylim = c(0, 100), expand = 0) +
scale_y_continuous(breaks = c(17, 35, 88))

### 5.2.6 Swap the axes

p2 <- p0 +
coord_flip()
p1 + p2