Module 3-1-Principle - Data Visualization with ggplot2 in R

Author

Vianey Villegas

Published

Invalid Date

1 Overview

1.1 Expected Learning Outcomes

After taking this workshop, participants should be able to do following:

  1. Explain the concept of the grammar of graphics when visualizing data with the ggplot2 package.

  2. Be familiar with various types of charts.

  3. Visualize data in counts and proportions.

  4. Select appropriate charts based on strategic considerations (e.g., the characteristics of the data and audience).

  5. Create a chart that involves one or two variables with either categorical or continuous data.

  6. Create a chart by adding a categorical moderator (3rd variable) to the chart involving two or three variables.

  7. Create correlation charts.

  8. Read charts and generate insights.

  9. Describe three popular packages that allow one to visualize data.

  10. Explain the concept of the grammar of graphics when visualizing data with the ggplot2 package.

1.2 Loading Packages

#install.packages("ggplot2")
#install.packages('ggrepel')
#install.packages('ggthemes')
#install.packages('scales')
#install.packages('plotly')
#install.packages('lattice')
#install.packages('GGally')
#install.packages("dplyr")
#install.packages("tidyverse")
#install.packages('ggtext')
#install.packages("glue")
library(ggplot2) #visualization
library(ggrepel) #labels for data
library(ggthemes) #collections of themes
library(scales) # scale
library(plotly) # interactive chart
library(GGally) # correlation
library(dplyr) # data transformation
library(tidyverse) # mega package containing 8 packages
library(ggtext) # for text visualization
library(glue) # combining multiple component
library(gapminder)

2 1. Understand mtcars data

2.1 1.1 Using Help

?mtcars 
help(mtcarz) 
No documentation for 'mtcarz' in specified packages and libraries:
you could try '??mtcarz'

A data frame with 32 observations on 11 (numeric) variables.

  • [, 1] mpg Miles/(US) gallon

  • [, 2] cyl Number of cylinders

  • [, 3] disp Displacement (cu.in.)

  • [, 4] hp Gross horsepower

  • [, 5] drat Rear axle ratio

  • [, 6] wt Weight (1000 lbs)

  • [, 7] qsec 1/4 mile time

  • [, 8] vs Engine (0 = V-shaped, 1 = straight)

  • [, 9] am Transmission (0 = automatic, 1 = manual)

  • [,10] gear Number of forward gears

  • [,11] carb Number of carburetors Note]

2.2 1.2 Reading data and converting to a tribble (cars)

head(mtcars) 
class(mtcars)

# short cut for pipe operator (%\>%, |>) : crl + shift + M

cars \<- mtcars |>
  rownames_to_column() |>
  as_tibble() |>
  rename(model = rowname) |>
  print(n=20, width = Inf) 
Error in parse(text = input): <text>:6:6: unexpected '\\'
5: 
6: cars \
        ^
Note

Shortcut for code chunk: ctrl + atl + i

# Using a built in plotting function
hist(cars$disp, breaks = 10)
Error in `hist.default()`:
! 'x' must be numeric

3 Lattice package

#install.paclages("lattice")
library(lattice)
xyplot(mpg ~ wt, cars)
Error:
! object 'wt' not found
histogram(cars$disp, breaks = 10)
Error in `UseMethod()`:
! no applicable method for 'histogram' applied to an object of class "NULL"

4 ggplot2

  • We will use ggplot2 - the best tool in the market for data visualization - from now on.

5 4.1 Elaborate examples

5.0.1 4.1.1 x & y are both continuous with moderator & labeller()

cars |> 
  count(cyl)
Error in `count()`:
! Must group by variables found in `.data`.
✖ Column `cyl` is not found.
cars |>
  ggplot(aes(x = mpg, y = disp, color = cyl)) +
  geom_point()
Error in `geom_point()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error:
! object 'disp' not found
cars |>
  count(cyl)
Error in `count()`:
! Must group by variables found in `.data`.
✖ Column `cyl` is not found.

5.0.1.1 Plotting

cars |>
  mutate(cyl = factor(cyl))) |>
  ggplot(aes(x = mpg, y = disp, color = cyl)) +
  geom_point() +
  geom_smooth(method = "ln", se = FALSE) +
  facet_wrap(~ cyl, nol = 1) +
  theme_bw()
Error in parse(text = input): <text>:2:28: unexpected ')'
1: cars |>
2:   mutate(cyl = factor(cyl)))
                              ^