Data visualization

the ggplot2 package, and the five named graphs

the grammar of graphics aes()

  • ggplot()
  • geom_point()
  • geom_line()
  • geom_histogram()
  • geom_boxplot()
  • geom_bar()

Every graph in this chapter is built from the same three pieces.

ggplot()

Name the data, say which variables to map, then add a layer saying what kind of graph to draw.

Scatterplot of arrival delay in minutes against departure delay in minutes for Envoy Air flights, one point per flight

ggplot()

Example

the verb (function) the data frame which variables to plot

ggplot(data = envoy_flights, mapping = aes(x = dep_delay, y = arr_delay)) +
  geom_point()

Scatterplot of arrival delay in minutes against departure delay in minutes for Envoy Air flights, one point per flight

what kind of graph to make

geom_histogram()

Example

the data frame which variable to plot

ggplot(data = weather, mapping = aes(x = wind_speed)) +
  geom_histogram()

Histogram of hourly wind speed in miles per hour at the three New York City airports, drawn with ggplot2's default 30 bins

what kind of graph to make

geom_histogram()

Adding graphical details. The extra arguments change how the bars are cut and colored, not what is plotted.

Example

ggplot(data = weather, mapping = aes(x = wind_speed)) +
  geom_histogram(binwidth = 5, boundary = 40, color = "white")

Histogram of hourly wind speed in miles per hour at the three New York City airports, with bars 5 miles per hour wide outlined in white

other graphical details

Summary of the five named graphs

Number Named graph Shows Geometric object Notes
1 Scatterplot Relationship between 2 numerical variables geom_point()
2 Linegraph Relationship between 2 numerical variables geom_line() Used when there is a sequential order to the x-variable, e.g. time
3 Histogram Distribution of 1 numerical variable geom_histogram() A faceted histogram shows the distribution of 1 numerical variable split by 1 categorical variable
4 Boxplot Distribution of 1 numerical variable split by 1 categorical variable geom_boxplot() To graph without splitting by a categorical variable add x = NULL
5 Barplot Distribution of 1 categorical variable geom_bar() when counts are not pre-counted, geom_col() when they are Stacked and dodged barplots show the distribution of 2 categorical variables