1. Viewing Dataset Samples

Head: First 6 rows of mtcars

head(mtcars)

Tail: Last 6 rows of mtcars

tail(mtcars)

2. Creating a Histogram of Miles per Gallon (mpg)

# Create the histogram
my_plot <- ggplot(mtcars, aes(x = mpg)) +
  geom_histogram(binwidth = 5, fill = "skyblue", color = "black") +
  xlab("Miles/Gallon") +
  ylab("Number of Cars") +
  ggtitle("Histogram of Fuel Efficiency (mpg)")
my_plot

✍️ Analysis of the Histogram

The histogram displays the distribution of fuel efficiency (miles per gallon) for various cars in the mtcars dataset.

  • The shape is slightly right-skewed, with the most frequent range being 15–20 mpg.
  • Indicates moderate fuel efficiency is common.
  • Fewer cars exceed 25 mpg, showing that high-efficiency cars are rare.

3. Creating a Boxplot of mpg by Number of Cylinders

# Convert cylinder count to ordered factor
mtcars <- mutate(mtcars, cyl = factor(cyl, ordered = TRUE, levels = c(4, 6, 8)))

# Create the boxplot
my_boxplot <- ggplot(mtcars, aes(x = cyl, y = mpg)) +
  geom_boxplot(fill = "orange", color = "darkred") +
  xlab("Cylinders") +
  ylab("Miles per Gallon") +
  ggtitle("Boxplot of mpg by Cylinder Count")
my_boxplot

✍️ Analysis of the Boxplot

The boxplot compares fuel efficiency across cars with different cylinder counts:

  • 4-cylinder cars: Show the highest mpg range (20–35 mpg), indicating better efficiency.
  • 6-cylinder cars: Mid-range mpg, clustering around 18–21 mpg.
  • 8-cylinder cars: Show the lowest mpg, between 14–16.5 mpg.

Conclusion: Fuel efficiency decreases with an increase in cylinder count, revealing the trade-off between engine power and mpg.