These exercises cover the sections of Plotting in R PlottingInR.

Section 1

Please load the dateset mtcars by calling data(mtcars) and use the base R graphics to

  1. create a scatter plot of mtcars$mpg VS mtcars$wt (x-axis = mpg and y-axis = wt).

  2. change the axis labels to x axis = “Miles/(US) gallon” and y axis = “Weight (1000 lbs)”

  3. add title = “scatter plot”

  4. change the colour of data points to red and the the shape of points to “filled circle”

[hint: use data() function to load mtcars]

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
plot(mtcars$mpg, mtcars$wt, main="scatter plot", xlab="Miles/(US) gallon", 
     ylab="Weight (1000 lbs)",pch=16,col="red")

Section 2

Please load the dateset mtcars by calling data(mtcars) and use ggplot2 to

  1. create a scatter plot of mtcars$mpg VS mtcars$wt (x-axis = mpg` and y-axis = wt).

  2. change the axis labels to x axis = “Miles/(US) gallon” and y axis = “Weight (1000 lbs)”

  3. add title = “scatter plot”

  4. change the colour of data points to red [hint: use col="red" when constructing aesthetic mappings]

library(ggplot2)
## Warning in register(): Can't find generic `scale_type` in package ggplot2 to
## register S3 method.
g <- ggplot(mtcars, aes(x=mpg,y=wt,col="red")) + geom_point()

# option 1
g + labs(x="Miles/(US) gallon",y="Weight (1000 lbs)",title="scatter plot - option 1")

# option 2
g + xlab("Miles/(US) gallon") + ylab("Weight (1000 lbs)") +
  ggtitle("scatter plot - option 2")

    1. what will happen if change the colour of points to mtcars$am [hint: use col=am when constructing aesthetic mappings]
library(ggplot2)
ggplot(mtcars, aes(x=mpg,y=wt,col=am))+ geom_point()

    1. what will happen if change the colour of points use col=as.factor(am) when constructing aesthetic mappings
library(ggplot2)
ggplot(mtcars, aes(x=mpg,y=wt,col=as.factor(am)))+ geom_point()