The mtcars dataset is a built-in dataset in R that
contains information about 32 different car models from the 1970s. Here
are the variables:
data(mtcars)
head(mtcars)
## mpg cyl disp hp drat wt qsec vs am gear carb
## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
We’ll plot miles per gallon (mpg) against
horsepower (hp), using point size to represent car
weight (wt) and alpha for transparency. We’ll
also add a linear regression line.
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point(aes(size = wt), alpha = 0.6, color = "steelblue") +
geom_smooth(method = "lm", se = FALSE, color = "darkred") +
labs(title = "Fuel Efficiency vs Horsepower",
x = "Horsepower",
y = "Miles per Gallon (mpg)",
size = "Weight (1000 lbs)") +
theme_minimal() +
theme(plot.background = element_rect(fill = "#f0f8ff"))
## `geom_smooth()` using formula = 'y ~ x'
Now we make the same plot interactive using
plotly::ggplotly().
plotly::ggplotly(
ggplot(mtcars, aes(x = hp, y = mpg, text = rownames(mtcars))) +
geom_point(aes(size = wt), alpha = 0.6, color = "steelblue") +
geom_smooth(method = "lm", se = FALSE, color = "darkred") +
labs(title = "Fuel Efficiency vs Horsepower",
x = "Horsepower",
y = "Miles per Gallon (mpg)",
size = "Weight (1000 lbs)") +
theme_minimal() +
theme(plot.background = element_rect(fill = "#f0f8ff"))
)
## `geom_smooth()` using formula = 'y ~ x'
We’ll simulate a time component using the row index to show how cars appear over time.
library(gifski)
library(gganimate)
mtcars$car <- rownames(mtcars)
mtcars$time <- 1:nrow(mtcars) # Simulated time sequence
p <- ggplot(mtcars, aes(x = hp, y = mpg, label = car)) +
geom_point(aes(size = wt), alpha = 0.6, color = "steelblue") +
geom_text(vjust = -1, size = 3) +
labs(title = 'Cars Over Time: Frame {frame_time}',
x = 'Horsepower',
y = 'Miles per Gallon (mpg)',
size = 'Weight') +
theme_minimal() +
theme(plot.background = element_rect(fill = "#f0f8ff")) +
transition_time(time) +
ease_aes('linear')
animate(p, renderer = gifski_renderer())
This project demonstrates how to visualize and interpret the
mtcars dataset using static, interactive, and animated
visualizations. The plots reveal that as horsepower increases, miles per
gallon tends to decrease, and heavier cars are typically less
fuel-efficient.