Healy Chapter 4 Part 1

Harold Nelson

9/24/2018

library(socviz)
library(gapminder)
library(tidyverse)
## ── Attaching packages ──────────────────────────────── tidyverse 1.2.1 ──
## ✔ ggplot2 3.0.0     ✔ purrr   0.2.5
## ✔ tibble  1.4.2     ✔ dplyr   0.7.6
## ✔ tidyr   0.8.1     ✔ stringr 1.3.1
## ✔ readr   1.1.1     ✔ forcats 0.3.0
## Warning: package 'dplyr' was built under R version 3.5.1
## ── Conflicts ─────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()

What is an Aesthetic?

Normally an aesthetic is a statement of the form visual attribute = variable. Visual attribute is something you can see like color or size. Variable refers to a column in the data frame.

There are two exceptions to this general pattern.

We may see the visual attribute slot filled by “group.” This is not a visual attribute. It’s an instruction as to how to structure the graph.

In some cases the variable slot is filled by something of the form ..xxxx.. .The two dots indicate that xxxx will not be found in the incoming dataframe, but will be constructed by ggplot2 prior to drawing the graphic.

Exercise

Look at the facet_wrap example in 4.3, GDP per capita on Five Continents. What happens if you copy this and re-run it? Can you fix the problems?

Answer

You can change fig.width and fig.height for this chunk. Note that there is a bug in the display of this in RStudio.

p = ggplot(data=gapminder,
           mapping = aes(x=year,y=gdpPercap)) 
p +  geom_line(aes(group = country),alpha=1) +
  geom_smooth(size = 1.1, method = "loess", se = FALSE) +
  facet_wrap(~continent,ncol=5) +
  scale_y_log10(labels=scales::dollar) +
  labs(x="year",
         y = "GDP per capita",
         title = "GDP per capita on Five Continents")

Exercises

Do as Healy suggests and remove the additional layers of the plot one-by-one. Observe what each of these did to the overall graph.

Exercise

Can you center the title?

Answer

p = ggplot(data=gapminder,
           mapping = aes(x=year,y=gdpPercap)) 
p +  geom_line(aes(group = country),alpha=1) +
  geom_smooth(size = 1.1, method = "loess", se = FALSE) +
  facet_wrap(~continent,ncol=5) +
  scale_y_log10(labels=scales::dollar) +
  labs(x="year",
         y = "GDP per capita",
         title = "GDP per capita on Five Continents") +
  theme(plot.title = element_text(hjust = 0.5))