Code
library(dplyr)
library(ggplot2)
library(tibble)A modern, accessible introduction using mtcars
Miguelangel Palma Rojas
November 15, 2026
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.
mtcars stores cylinders, transmission, and gears as numbers. They are categories for this analysis, so the code converts them to factors before plotting.
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.
Use bars when the question is how many observations belong to each group.
The bin width controls the level of detail and should be chosen explicitly.
Color and shape provide redundant category encodings. The fitted line summarizes association, not causality.
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
The box plot summarizes each distribution while jittered points preserve the small sample.
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
See the Spanish version.
---
title: "Creating Effective Visualizations with ggplot2"
subtitle: "A modern, accessible introduction using mtcars"
author: "Miguelangel Palma Rojas"
date: last-modified
lang: en
---
## 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
```{r}
#| label: packages
#| message: false
#| warning: false
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.
```{r}
#| label: prepare-data
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)
```
The prepared dataset contains `r nrow(cars)` vehicles and `r ncol(cars)` variables.
```{r}
#| label: chart-theme
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.
```{r}
#| label: cylinder-bars
#| fig-alt: "Bar chart showing the number of cars with four, six, and eight cylinders."
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
```
## Histogram: inspect a continuous distribution
The bin width controls the level of detail and should be chosen explicitly.
```{r}
#| label: horsepower-histogram
#| fig-alt: "Histogram of horsepower values in the mtcars dataset."
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
```
## Scatter plot: examine two numeric variables
Color and shape provide redundant category encodings. The fitted line summarizes association, not causality.
```{r}
#| label: efficiency-scatter
#| fig-alt: "Scatter plot of vehicle weight and fuel efficiency, colored by cylinder count and shaped by transmission."
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
```
## Box plot: compare distributions across groups
The box plot summarizes each distribution while jittered points preserve the small sample.
```{r}
#| label: efficiency-boxplot
#| fig-alt: "Box plots comparing fuel efficiency for automatic and manual transmissions."
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
```
## Conclusion
- The sample is structurally imbalanced: `r sum(cars$cylinders == "8")` of `r nrow(cars)` vehicles have eight cylinders, compared with `r sum(cars$cylinders == "6")` six-cylinder vehicles. This explains why count comparisons should precede distributional comparisons.
- Vehicle weight and fuel efficiency have a Pearson correlation of `r round(cor(cars$wt, cars$mpg), 3)`, indicating a strong negative linear association in this sample.
- Manual-transmission vehicles average `r round(mean(cars$mpg[cars$am == 1]), 1)` mpg versus `r round(mean(cars$mpg[cars$am == 0]), 1)` mpg for automatics, a difference of `r round(mean(cars$mpg[cars$am == 1]) - mean(cars$mpg[cars$am == 0]), 1)` 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](es/index.qmd).