Chapter 3 Data Visualization

  1. ggplot2
  2. scatterplots, points, color, shape
  3. faceting

Today we are going to try some of the code from Chapter 3 Data Visualization.

To start we will load the tidyverse. Note that ggplot2 is the first package loaded!

library(tidyverse)

We will start the mpg dataset that is in the ggplot2 package.

mpg

Make a scatterplot of highway miles per gallon (hwy) and engine size (displ).

Start with an empty graph and add to it.

ggplot(data = mpg)

Add points using geom_point mapping and aesthetic.

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy))

Add color.

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy, color = class))

Change size of the points.

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy, size = class))

Change the transparentcy or shape.

# Left
ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy, alpha = class))

# Right
ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy, shape = class))

Specify color.

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy), color = "blue")

Faceting, spliting a plot into separate plots for different levels of a categorical variable.

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy)) + 
  facet_wrap(~ class, nrow = 2)

LS0tCnRpdGxlOiAiRXhwbG9yZSBhbmQgVmlzdWFsaXplIgphdXRob3I6ICJQcm9mLiBFcmljIEEuIFN1ZXNzIgpvdXRwdXQ6CiAgd29yZF9kb2N1bWVudDogZGVmYXVsdAogIGh0bWxfZG9jdW1lbnQ6CiAgICBkZl9wcmludDogcGFnZWQKICBwZGZfZG9jdW1lbnQ6IGRlZmF1bHQKICBodG1sX25vdGVib29rOiBkZWZhdWx0Ci0tLQoKIyBDaGFwdGVyIDMgRGF0YSBWaXN1YWxpemF0aW9uCgoxLiBnZ3Bsb3QyCjIuIHNjYXR0ZXJwbG90cywgcG9pbnRzLCBjb2xvciwgc2hhcGUKMy4gZmFjZXRpbmcKClRvZGF5IHdlIGFyZSBnb2luZyB0byB0cnkgc29tZSBvZiB0aGUgY29kZSBmcm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