• 1 ggplot2 and the grammar of graphics
    • 1.1 geom_bar() … the bar-chart
    • 1.2 color versus fill
    • 1.3 Adding labels with labs
    • 1.4 Controlling the chart legend with theme()
    • 1.5 Customizing colors
    • 1.6 Selected color palettes
    • 1.7 Themes with {ggthemes}
    • 1.8 More with bar-charts
    • 1.9 Disaggregating bar-charts for groups
    • 1.10 Histograms
    • 1.11 Box-plots
    • 1.12 Line-charts
    • 1.13 Scatter-plots
  • 2 Practice Exercises
    • 2.1 Nobel Prize Winners
    • 2.2 Water levels in the Great Lakes
    • 2.3 County Health Rankings
    • 2.4 Unemployment Rates

Our goal in this module is to understand some basic ways of visualizing data with graphics – bar-charts, histograms, box-plots, and so on. We will skip base R commands and instead just work with ggplot2, the most popular visualization package in the {tidyverse} universe as of now.

If you remember MPA 6010, recall the usual options…

  • one qualitative/categorical variables: bar-chart
  • one quantitative/continuous variables: histogram/box-plot/area-chart
  • two quantitative/continuous variables: scatter-plot/hex-bin

We can then ratchet up as we need to.

I will use two data-sets to walk through the initial examples in this module, the first being this IMDB data-set

The internet movie database, http://imdb.com/, is a website devoted to collecting movie data supplied by studios and fans. It claims to be the biggest movie database on the web and is run by amazon. More about information imdb.com can be found online, http://imdb.com/help/show_ leaf?about, including information about the data collection process, http://imdb.com/help/show_leaf?infosource.

library(ggplot2movies)
data(movies)
names(movies)
##  [1] "title"       "year"        "length"      "budget"      "rating"     
##  [6] "votes"       "r1"          "r2"          "r3"          "r4"         
## [11] "r5"          "r6"          "r7"          "r8"          "r9"         
## [16] "r10"         "mpaa"        "Action"      "Animation"   "Comedy"     
## [21] "Drama"       "Documentary" "Romance"     "Short"

A data frame with 28819 rows and 24 variables

Variable Description
title Title of the movie
year Year of release
budget Total budget (if known) in US dollars
length Length in minutes
rating Average IMDB user rating
votes Number of IMDB users who rated this movie
r1-10 Multiplying by ten gives percentile (to nearest 10%) of users who rated this movie a 1
mpaa MPAA rating (missing for a lot of movies)
action, animation, comedy, drama, documentary, romance, short Binary variables representing if movie was classified as belonging to that genre

The second data-set is the Star Wars dataset, a tibble with 87 rows and 13 variables:

library(tidyverse)
data(starwars)
names(starwars)
##  [1] "name"       "height"     "mass"       "hair_color" "skin_color"
##  [6] "eye_color"  "birth_year" "gender"     "homeworld"  "species"   
## [11] "films"      "vehicles"   "starships"
# str(starwars)
Variable Description
name Name of the character
height Height (cm)
mass Weight (kg)
hair_color, skin_color, eye_color Hair, skin, and eye colors
birth_year Year born (BBY = Before Battle of Yavin)
gender male, female, hermaphrodite, or none
homeworld Name of homeworld
species Name of species
films List of films the character appeared in
vehicles List of vehicles the character has piloted
starships List of starships the character has piloted

1 ggplot2 and the grammar of graphics

The {ggplot2} package has a special syntax and I will point out things you should note as we move through this module. First up, the library is called ggplot2 but the command starts with ggplot so don’t let that throw you off-track.

Second, you need to have a data-set to work with. In the code below I start by loading the library and then specifying the data-set to be used.

library(ggplot2)
ggplot(
  data = starwars
  )

Nothing results from these commands because we have not yet specified anything about what should go on the x-axis, what should go on the y-axis. Well, let us do that then by asking for the column eye_color to be put on the x-axis.

ggplot(
  data = starwars,
  mapping = aes(
    x = eye_color
    )
  ) 

1.1 geom_bar() … the bar-chart

This results in a gray canvas with the eye colors on the x-axis but nothing else has been drawn since we have not specified the geometry … do you want a bar-chart? histogram? dot-plot? line-chart? This is a categorical variable and hence a bar-chart would be appropriate. We call for a bar-chart with the geom_bar() command.

ggplot(
  data = starwars,
  mapping = aes(
    x = eye_color
    )
  ) +
  geom_bar()

1.2 color versus fill

The aes() refers to the aesthetics of the chart, and many other aesthetics can be added, such as group, color, fill, size, alpha, etc. We will see some of these in due course but for now I want to focus on two of these, both involving coloring of the geom_. Specifically, there are two commands for adding colors – (1) color or colour, and (2) fill – to a chart.

ggplot(
  data = starwars,
  mapping = aes(
    x = eye_color,
    color = eye_color
    )
  ) +
  geom_bar()

Note what the color = eye_color command did … it drew a colored border for the bars, and an accompanying legend. What if we had used fill = eye_color instead?

ggplot(
  data = starwars,
  mapping = aes(
    x = eye_color,
    fill = eye_color
    )
  ) +
  geom_bar()

Aha! Now the bars are filled with colors and an accompanying legend is drawn as well. So fill = and color = behave very differently, bear this in mind.

1.3 Adding labels with labs

One of the nice things about this software environment is that there are plenty of coloring schemes available to us and we will play with some of these shortly, but before we do that, let us look at one more improvement – adding titles, subtitles, captions, and axis labels to our chart. This is done with the labs = () command.

ggplot(
  data = starwars,
  mapping = aes(
    x = eye_color,
    fill = eye_color
    )
  ) +
  geom_bar() +
  labs(
    x = "Eye Color",
    y = "Frequency (n)",
    title = "Bar-chart of Eye Colors",
    subtitle = "(of Star Wars characters)",
    caption = "My little work of art!!"
    )

Notice the text that now appears as a result of what has been specified in the labs() command.

1.4 Controlling the chart legend with theme()

In this bar-chart, do we really need the legend? No, because the colors and color names show up in the chart itself. How can we hide the legend? Turns out there is a neat command that will allow you to move the legend around and even to hide it.

ggplot(
  data = starwars,
  mapping = aes(
    x = eye_color,
    fill = eye_color
    )
  ) +
  geom_bar() +
  labs(
    x = "Eye Color",
    y = "Frequency (n)",
    title = "Bar-chart of Eye Colors",
    subtitle = "(of Star Wars characters)",
    caption = "My little work of art!!"
    ) +
  theme(legend.position = "none")

Voila! The legend is gone. Instead of “none” you could have specified “bottom”, “left”, “top”, “right” to place the legend in a particular direction.

1.5 Customizing colors

Of course, it would be good to have the colors match the eye-color so let us do that next. The way we can do this is by calling specific colors by name. I have tried to order the lineup of the colors to match, as closely as I can, the eye colors.

c(
  "black", "blue", "slategray", "brown", "gray34", "gold",
  "greenyellow", "navajowhite1", "orange", "pink", "red",
  "magenta", "thistle3", "white", "yellow"
  ) -> mycolors

ggplot(
  data = starwars,
  mapping = aes(
    x = eye_color
    )
  ) + 
  geom_bar(
    fill = mycolors
    ) + 
  labs(
    x = "Eye Color",
    y = "Frequency (n)",
    title = "Bar-chart of Eye Colors",
    subtitle = "(of Star Wars characters)",
    caption = "My little work of art!!"
    ) +
  theme(legend.position = "none")

These colors are from this source but see also this source. Colors can be customized by generating your own palettes via the Color Brewer here. But don’t get carried away: Remember to read the materials on choosing colors wisely, particularly the point about qualitative palettes, divergent palettes, and then palettes that work well even with colorblind audiences.

1.6 Selected color palettes

I had mentioned the existence of a number of color palettes so let us look at a few, but we will do this with a different variable. First up, the Pastel1 palette.

ggplot(
  data = starwars,
  mapping = aes(
    x = gender
    )
  ) + 
  geom_bar(
    aes(fill = gender)
    ) + 
  labs(
    x = "Gender",
    y = "Frequency",
    title = "Bar-chart of Gender",
    subttitle = "(of Star Wars characters)",
    caption = "(Source: The dplyr package)") +
  scale_fill_brewer(
    palette = "Pastel1"
    )