Dataset
We are using the built-in mtcars dataset. It contains 32 cars with 11 attributes:
mpg = Miles per gallon cyl = Number of cylinders disp = Displacement
hp = Horsepower drat = Rear axle ratio wt = Weight qsec = Quarter-mile
time vs = Engine shape am = Transmission gear = Number of forward gears
carb = Number of carburetors dat <- as_tibble(mtcars) dat Figure 1:
Scatterplot of Weight vs MPG ggplot(dat, aes(x = wt, y = mpg)) +
geom_point(color = “blue”, size = 3) + labs( title = “Scatterplot: Car
Weight vs Miles per Gallon”, x = “Weight (1000 lbs)”, y = “Miles per
Gallon” ) + theme_minimal() Figure 2: Boxplot of MPG by Number of
Cylinders ggplot(dat, aes(x = factor(cyl), y = mpg, fill = factor(cyl)))
+ geom_boxplot() + labs( title = “Boxplot: MPG by Cylinder Count”, x =
“Number of Cylinders”, y = “Miles per Gallon”, fill = “Cylinders” ) +
theme_minimal() Figure 3: Histogram of Horsepower ggplot(dat, aes(x =
hp)) + geom_histogram(binwidth = 20, fill = “orange”, color = “black”) +
labs( title = “Histogram of Horsepower”, x = “Horsepower”, y = “Count” )
+ theme_minimal() Figure 4: Density Plot of Quarter-Mile Time
ggplot(dat, aes(x = qsec, fill = factor(cyl))) + geom_density(alpha =
0.5) + labs( title = “Density of Quarter-Mile Times by Cylinder Count”,
x = “Quarter-Mile Time (seconds)”, y = “Density”, fill = “Cylinders” ) +
theme_minimal() Figure 5: Bar Chart of Number of Cars by Gear
ggplot(dat, aes(x = factor(gear), fill = factor(gear))) + geom_bar() +
labs( title = “Number of Cars by Gear Count”, x = “Number of Gears”, y =
“Count”, fill = “Gears” ) + theme_minimal() Figure 6: Line Plot of MPG
vs HP ggplot(dat, aes(x = hp, y = mpg)) + geom_line(color = “darkgreen”)
+ geom_point(size = 2) + labs( title = “Line Plot: MPG vs Horsepower”, x
= “Horsepower”, y = “Miles per Gallon” ) + theme_minimal() Figure 7:
Scatterplot Matrix (Pairs Plot) – Interactive with Plotly p <-
ggplot(dat, aes(x = wt, y = mpg, text = paste(“HP:”, hp, “
Cyl:”,
cyl))) + geom_point(aes(color = factor(cyl)), size = 3) + labs( title =
“Interactive Scatterplot: Weight vs MPG by Cylinder Count”, x =
“Weight”, y = “MPG”, color = “Cylinders” ) + theme_minimal()
ggplotly(p) Figure 8: Animated Scatterplot of Weight vs MPG (Optional – gganimate) library(gganimate) anim <- ggplot(dat, aes(x = wt, y = mpg, size = hp, color = factor(cyl))) + geom_point(alpha = 0.7) + labs( title = ‘Car Weight vs MPG: Frame {frame_time}’, x = ‘Weight (1000 lbs)’, y = ‘Miles per Gallon’, color = ‘Cylinders’, size = ‘Horsepower’ ) + transition_states(states = factor(cyl), transition_length = 2, state_length = 1) + ease_aes(‘linear’)
anim
Note: The last figure uses gganimate and may require installing gifski and png packages. If you cannot run it, you can skip and keep the interactive Plotly figure as your “interactive/animated” requirement.