R R

R: Plotting with Base R & ggplot2

What you will learn

R has powerful built-in plotting (base R graphics) and an even more popular package, ggplot2. You'll also learn the tidyverse — a collection of packages for modern R.

Base R plotting

x <- 1:10
y <- x^2

plot(x, y, type = "l", col = "blue", main = "Square Function")

# Histogram
hist(rnorm(100), main = "Normal Distribution", col = "lightblue")

# Boxplot
boxplot(mtcars$mpg ~ mtcars$cyl,
        main = "MPG by Cylinders",
        xlab = "Cylinders", ylab = "Miles Per Gallon")

The grammar of graphics: ggplot2

ggplot2 is the most popular R graphics package. It uses a layered approach:

library(ggplot2)

ggplot(mtcars, aes(x = wt, y = mpg)) +
    geom_point() +
    geom_smooth(method = "lm") +
    labs(title = "Weight vs MPG", x = "Weight", y = "MPG")

The tidyverse

The tidyverse is a collection of R packages designed for data science:

Package Purpose
dplyr Data manipulation (filter, select, mutate, summarize)
tidyr Data tidying (pivot, separate, unite)
ggplot2 Data visualization
readr Reading data (CSV, TSV, etc.)
purrr Functional programming
tibble Modern data frames
library(dplyr)

mtcars %>%
    filter(mpg > 20) %>%
    select(mpg, hp, wt) %>%
    summarise(avg_mpg = mean(mpg))

The %>% (pipe) operator passes the result on the left as the first argument of the function on the right.

Common mistakes

  • Forgetting library(ggplot2) before using ggplot functions.
  • Using = inside aes() instead of == for conditions — aes() expects column names, not logical expressions.
  • Not installing packages first — install.packages("ggplot2") before library(ggplot2).
  • Mixing base R and tidyverse pipe operators — |> (base R 4.1+) vs %>% (magrittr/tidyverse).

Quick check below!