Skip to main content

Creating Effective Visualizations with ggplot2

A modern, accessible introduction using mtcars

Author

Miguelangel Palma Rojas

Published

November 15, 2026

Objective

This notebook shows every analytical step directly. The code prepares the data, checks its structure, and builds four chart types with the explicit ggplot2 grammar.

Load packages

Code
library(dplyr)
library(ggplot2)
library(tibble)

Prepare variables deliberately

mtcars stores cylinders, transmission, and gears as numbers. They are categories for this analysis, so the code converts them to factors before plotting.

Code
required_columns <- c("mpg", "cyl", "hp", "wt", "am", "gear")
missing_columns <- setdiff(required_columns, names(mtcars))

if (length(missing_columns) > 0) {
  stop("Missing required columns: ", paste(missing_columns, collapse = ", "))
}

cars <- mtcars |>
  rownames_to_column("model") |>
  mutate(
    cylinders = factor(cyl, levels = c(4, 6, 8)),
    transmission = factor(
      am,
      levels = c(0, 1),
      labels = c("Automatic", "Manual")
    ),
    gears = factor(gear)
  )

glimpse(cars)
Rows: 32
Columns: 15
$ model        <chr> "Mazda RX4", "Mazda RX4 Wag", "Datsun 710", "Hornet 4 Dri…
$ mpg          <dbl> 21.0, 21.0, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19.…
$ cyl          <dbl> 6, 6, 4, 6, 8, 6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, …
$ disp         <dbl> 160.0, 160.0, 108.0, 258.0, 360.0, 225.0, 360.0, 146.7, 1…
$ hp           <dbl> 110, 110, 93, 110, 175, 105, 245, 62, 95, 123, 123, 180, …
$ drat         <dbl> 3.90, 3.90, 3.85, 3.08, 3.15, 2.76, 3.21, 3.69, 3.92, 3.9…
$ wt           <dbl> 2.620, 2.875, 2.320, 3.215, 3.440, 3.460, 3.570, 3.190, 3…
$ qsec         <dbl> 16.46, 17.02, 18.61, 19.44, 17.02, 20.22, 15.84, 20.00, 2…
$ vs           <dbl> 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, …
$ am           <dbl> 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, …
$ gear         <dbl> 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, …
$ carb         <dbl> 4, 4, 1, 1, 2, 1, 4, 2, 2, 4, 4, 3, 3, 3, 4, 4, 4, 1, 2, …
$ cylinders    <fct> 6, 6, 4, 6, 8, 6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, …
$ transmission <fct> Manual, Manual, Manual, Automatic, Automatic, Automatic, …
$ gears        <fct> 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, …

The prepared dataset contains 32 vehicles and 15 variables.

Code
chart_theme <- theme_minimal(base_size = 12) +
  theme(
    plot.title.position = "plot",
    plot.title = element_text(face = "bold"),
    panel.grid.minor = element_blank(),
    legend.position = "bottom"
  )

Bar chart: compare category counts

Use bars when the question is how many observations belong to each group.

Code
ggplot(cars, aes(x = cylinders, fill = cylinders)) +
  geom_bar(show.legend = FALSE) +
  scale_fill_viridis_d(end = 0.85) +
  labs(
    title = "Cars by cylinder count",
    x = "Cylinders",
    y = "Cars"
  ) +
  chart_theme

Bar chart showing the number of cars with four, six, and eight cylinders.

Histogram: inspect a continuous distribution

The bin width controls the level of detail and should be chosen explicitly.

Code
ggplot(cars, aes(x = hp)) +
  geom_histogram(
    binwidth = 25,
    boundary = 0,
    fill = "#2A9D8F",
    color = "white"
  ) +
  labs(
    title = "Horsepower distribution",
    x = "Horsepower",
    y = "Cars"
  ) +
  chart_theme

Histogram of horsepower values in the mtcars dataset.

Scatter plot: examine two numeric variables

Color and shape provide redundant category encodings. The fitted line summarizes association, not causality.

Code
ggplot(
  cars,
  aes(
    x = wt,
    y = mpg,
    color = cylinders,
    shape = transmission
  )
) +
  geom_point(size = 3, alpha = 0.85) +
  geom_smooth(
    aes(group = 1),
    method = "lm",
    se = TRUE,
    color = "#333333"
  ) +
  scale_color_viridis_d(end = 0.85) +
  labs(
    title = "Fuel efficiency falls as vehicle weight rises",
    subtitle = "Point shape identifies transmission type",
    x = "Weight (1,000 lb)",
    y = "Fuel efficiency (mpg)",
    color = "Cylinders",
    shape = "Transmission"
  ) +
  chart_theme

Scatter plot of vehicle weight and fuel efficiency, colored by cylinder count and shaped by transmission.

Box plot: compare distributions across groups

The box plot summarizes each distribution while jittered points preserve the small sample.

Code
ggplot(cars, aes(x = transmission, y = mpg, fill = transmission)) +
  geom_boxplot(width = 0.6, show.legend = FALSE) +
  geom_jitter(width = 0.08, alpha = 0.65) +
  scale_fill_viridis_d(end = 0.85) +
  labs(
    title = "Fuel efficiency by transmission",
    x = "Transmission",
    y = "Fuel efficiency (mpg)"
  ) +
  chart_theme

Box plots comparing fuel efficiency for automatic and manual transmissions.

Conclusion

  • The sample is structurally imbalanced: 14 of 32 vehicles have eight cylinders, compared with 7 six-cylinder vehicles. This explains why count comparisons should precede distributional comparisons.
  • Vehicle weight and fuel efficiency have a Pearson correlation of -0.868, indicating a strong negative linear association in this sample.
  • Manual-transmission vehicles average 24.4 mpg versus 17.1 mpg for automatics, a difference of 7.2 mpg. This is descriptive rather than causal because transmission is confounded with weight, cylinders, and vehicle design.
  • The layered charts therefore support a consistent technical finding: heavier, higher-cylinder vehicles dominate the low-efficiency region, while transmission-level differences require multivariable analysis before causal interpretation.

See the Spanish version.