Chapter 16 Revisiting earlier graphs 2

In this section, we’ll revisit earlier graphs (and make some new ones), and we’ll change some features of those graphs. Particularly, we’ll focus on changing scales and colours, and we’ll look at facets again.

16.1 scales

Read the section Scales, Axes & Coordinate systems.

Let’s put it to good use.

16.1.1 log-transformation

library(gapminder)
ggplot(gapminder, aes(x = pop)) +
  geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

ggplot(gapminder, aes(x = pop)) +
  geom_histogram() +
  scale_x_continuous(trans = "log10")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Let’s go further:

library(scales)
ggplot(gapminder, aes(x = pop)) +
  geom_histogram() +
  scale_x_continuous(
    trans = "log10",
    labels = trans_format("log10", math_format(10^.x))
  )

16.1.2 coord_fixed

heights <- read.csv("https://stulp.gmw.rug.nl/dataviz/heights.csv",
                    header = TRUE)

ggplot(heights, aes(x = HeightFemale, y = HeightMale)) +
  geom_bin2d(binwidth = c(1, 1)) +
  geom_smooth(method = "lm") +
  coord_fixed()
## `geom_smooth()` using formula = 'y ~ x'

16.2 colours

Read the section colours.

Let’s add a palette from RColourBrewer:

ggplot(mpg, aes(x = cty, fill = drv)) +
  geom_density() +
  scale_fill_brewer(palette = "Set1")

Let’s try again:

ggplot(mpg, aes(x = cty, fill = manufacturer)) +
  geom_density() +
  scale_fill_brewer(palette = "Set1")
## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Set1 is 9
## Returning the palette you asked for with that many colors

What’s going on here?

ggplot(mpg, aes(x = cty, fill = class)) +
  geom_density() +
  scale_fill_brewer(palette = "Set1")

Let’s see another example:

ggplot(mpg, aes(x = displ, y = cty, colour = drv)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  scale_colour_brewer(palette = "Set2")
## `geom_smooth()` using formula = 'y ~ x'

ggplot(mpg, aes(x = displ, y = cty, colour = drv)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  scale_colour_manual(values = c("green", "blue"))
Error: Insufficient values in manual scale. 3 needed but only 2 provided.

16.3 facets

Read the section Facets.

Example:

ggplot(mpg, aes(x = displ, y = cty, colour = drv)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  scale_colour_brewer(palette = "Set2") +
  facet_grid(~ drv)
## `geom_smooth()` using formula = 'y ~ x'