Instructions

In Chapter 12, we explored many different ways to “look at” the numbers. For this lab, let’s explore the mtcars dataset that is included within R.

This activity description does not provide the same level of code prompts as previous labs – it is assumed that you remember or can look up the necessary code. The overall goal of this activity is to use ggplot2 to show different attributes of the mtcars dataset. Please be sure to include both the code and the images that were generated with your assignment.

Add all of your libraries that you use for this assignment here.

# Add your library below.

library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.4.3

Generate the following visualizations:

Step 1 - Histogram

Histogram of mpg

# Write your code below.
ggplot(mtcars, aes(x = mpg)) +
     geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.


Step 2 - Boxplots

Boxplots of mpg by cyl (i.e. 3 box plots: one for all cars with 4 cylinders, one for all cars with 6 cylinders, and one with all the cars with 8 cylinders).

ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
    geom_boxplot()


Step 3 - MultiLine chart

MultiLine chart of wt on the x-axis, mpg for the y-axis. With a line for each am (i.e. two lines). Also be sure to show each point on the chart.

# Write your code below.
 ggplot(mtcars, aes(x = wt, y = mpg, group = am, color = factor(am))) +
     geom_line() +
     geom_point()


Step 4 - Barchart

Barchart with the x-axis being the name of each car, and the height being wt. Make sure to rotate the x-axis labels, so we can actually read the car name.

ggplot(mtcars, aes(x = rownames(mtcars), y = wt)) +
     geom_col() +
     geom_text(aes(label = wt), vjust = -0.3) +
     theme(axis.text.x = element_text(angle = 90))


Step 5 - Scatter chart

Scatter chart with the x-axis being the mpg and the y-axis being the wt of the car. Have the color and the size of each “symbol” (i.e., circle) represent how fast the car goes (based on the qsec attribute).

# Write your code below.
ggplot(mtcars, aes(x = mpg, y = wt, size = qsec, color = qsec)) +
     geom_point()

#AI Usage statement I did not use AI to generate complete solutions or finished code for this assignment. I first attempted all tasks independently using the textbook and course materials. After encountering syntax errors and visualization issues, I used ChatGPT as a learning aid to help clarify ggplot2 concepts, understand error messages, and debug my code. All code was written, tested, and revised by me, and I can explain each visualization and aesthetic choice in my own words.