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

Author

Mia Cortez

Published

February 18, 2026

Overview

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.

#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")
#install.packages("gapminder")
#install.packages("tibble")
#install.packages("magrittr")
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)
library(tibble)

1. Understand mtcars data

1.1 Using Help

?mtcars

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]

1.2 Reading data and converting to a tibble (cars)

head(mtcars)
class(mtcars)
[1] "data.frame"
mtcars
cars <- 
  mtcars %>% # piping operator from dplyr (shortcut: Ctrl+Shift+M)
  rownames_to_column() %>% # do this before changing the data to tibble as the conv %>% 
  ersion will remove rownames in tibble.
    as_tibble() %>%  
    rename(model = rowname) %>% 
    print (n = 20, width = Inf)
Error in parse(text = input): <text>:4:10: unexpected symbol
3:   rownames_to_column() %>% # do this before changing the data to tibble as the conv %>% 
4:   ersion will
            ^
cars 

**1.3 Simple Descriptive Statistics

summary(cars)
     speed           dist       
 Min.   : 4.0   Min.   :  2.00  
 1st Qu.:12.0   1st Qu.: 26.00  
 Median :15.0   Median : 36.00  
 Mean   :15.4   Mean   : 42.98  
 3rd Qu.:19.0   3rd Qu.: 56.00  
 Max.   :25.0   Max.   :120.00  
glimpse(cars)
Rows: 50
Columns: 2
$ speed <dbl> 4, 4, 7, 7, 8, 9, 10, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13…
$ dist  <dbl> 2, 10, 4, 22, 16, 10, 18, 26, 34, 17, 28, 14, 20, 24, 28, 26, 34…
skimr::skim(cars)
Data summary
Name cars
Number of rows 50
Number of columns 2
_______________________
Column type frequency:
numeric 2
________________________
Group variables None

Variable type: numeric

skim_variable n_missing complete_rate mean sd p0 p25 p50 p75 p100 hist
speed 0 1 15.40 5.29 4 12 15 19 25 ▂▅▇▇▃
dist 0 1 42.98 25.77 2 26 36 56 120 ▅▇▅▂▁

Basic Plotting Methods in Base R

# Using a built in plotting function
hist(cars$dist, breaks = 10)

3. Lattice package

library(lattice)
xyplot(mpg ~ wt, data = mtcars)

4. ggplot2

  • we will use ggplot2 – the best tool in the market for data visualization – from now on

4.1. Elaborate Example

Data wrangling

Plotting

cars |> 
  count(cyl)
Error in `count()`:
! Must group by variables found in `.data`.
✖ Column `cyl` is not found.
easy_labels <- c("4" = "4 Cylinder Cars",
                 "6" = "6 Cylinder Cars",
                 "8" = "8 Cylinder Cars"
                 )

cars |> 
  ggplot(aes(x = mpg, y = disp, color = factor(cyl))) +
  geom_point(size = 3,
             color = "black"
             ) +
  geom_smooth(method = lm, se = FALSE) +
  facet_wrap(~ cyl,
             ncol = 1) +
  theme_bw()
Error in `combine_vars()`:
! At least one layer must contain all faceting variables: `cyl`
✖ Plot is missing `cyl`
✖ Layer 1 is missing `cyl`
✖ Layer 2 is missing `cyl`
cars <- 
  mtcars |>  # piping operator from dplyr (shortcut: Ctrl+Shift+M)
    rownames_to_column() %>% # do this before changing the data to tibble as the conversion will remove rownames in tibble.
    as_tibble() |>   
    rename(model = rowname) |>  
    print (n = 20, width = Inf)
# A tibble: 32 × 12
   model                 mpg   cyl  disp    hp  drat    wt  qsec    vs    am
   <chr>               <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1 Mazda RX4            21       6 160     110  3.9   2.62  16.5     0     1
 2 Mazda RX4 Wag        21       6 160     110  3.9   2.88  17.0     0     1
 3 Datsun 710           22.8     4 108      93  3.85  2.32  18.6     1     1
 4 Hornet 4 Drive       21.4     6 258     110  3.08  3.22  19.4     1     0
 5 Hornet Sportabout    18.7     8 360     175  3.15  3.44  17.0     0     0
 6 Valiant              18.1     6 225     105  2.76  3.46  20.2     1     0
 7 Duster 360           14.3     8 360     245  3.21  3.57  15.8     0     0
 8 Merc 240D            24.4     4 147.     62  3.69  3.19  20       1     0
 9 Merc 230             22.8     4 141.     95  3.92  3.15  22.9     1     0
10 Merc 280             19.2     6 168.    123  3.92  3.44  18.3     1     0
11 Merc 280C            17.8     6 168.    123  3.92  3.44  18.9     1     0
12 Merc 450SE           16.4     8 276.    180  3.07  4.07  17.4     0     0
13 Merc 450SL           17.3     8 276.    180  3.07  3.73  17.6     0     0
14 Merc 450SLC          15.2     8 276.    180  3.07  3.78  18       0     0
15 Cadillac Fleetwood   10.4     8 472     205  2.93  5.25  18.0     0     0
16 Lincoln Continental  10.4     8 460     215  3     5.42  17.8     0     0
17 Chrysler Imperial    14.7     8 440     230  3.23  5.34  17.4     0     0
18 Fiat 128             32.4     4  78.7    66  4.08  2.2   19.5     1     1
19 Honda Civic          30.4     4  75.7    52  4.93  1.62  18.5     1     1
20 Toyota Corolla       33.9     4  71.1    65  4.22  1.84  19.9     1     1
    gear  carb
   <dbl> <dbl>
 1     4     4
 2     4     4
 3     4     1
 4     3     1
 5     3     2
 6     3     1
 7     3     4
 8     4     2
 9     4     2
10     4     4
11     4     4
12     3     3
13     3     3
14     3     3
15     3     4
16     3     4
17     3     4
18     4     1
19     4     2
20     4     1
# ℹ 12 more rows