Directions

During ANLY 512 we will be studying the theory and practice of data visualization. We will be using R and the packages within R to assemble data and construct many different types of visualizations. We begin by studying some of the theoretical aspects of visualization. To do that we must appreciate the basic steps in the process of making a visualization.

The objective of this assignment is to introduce you to R markdown and to complete and explain basic plots before moving on to more complicated ways to graph data.

The final product of your homework (this file) should include a short summary of each graphic.

To submit this homework you will create the document in Rstudio, using the knitr package (button included in Rstudio) and then submit the document to your Rpubs account. Once uploaded you will submit the link to that document on Canvas. Please make sure that this link is hyperlinked and that I can see the visualization and the code required to create it.

Part 1 - ggplot Basics

Find the mtcars data in R. This is the dataset that you will use to create your graphics.

mtcars <- datasets::mtcars
str(mtcars)
## 'data.frame':    32 obs. of  11 variables:
##  $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
##  $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
##  $ disp: num  160 160 108 258 360 ...
##  $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
##  $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
##  $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
##  $ qsec: num  16.5 17 18.6 19.4 17 ...
##  $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
##  $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
##  $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
##  $ carb: num  4 4 1 1 2 1 4 2 2 4 ...
mtcars$vs <- as.factor(mtcars$vs) # change to factor
mtcars$am <- as.factor(mtcars$am) # change to factor
  1. Create a box plot using ggplot showing the range of values of 1/4 mile time (qsec) for each tansmission type (am, 0 = automatic, 1 = manual) from the mtcars data set.
library(ggplot2)
library(ggthemes)
boxplot <- ggplot(data = mtcars, aes(x=am, y=qsec)) +
  geom_boxplot()+
  xlab("Engine")+
  ylab("1/4 Mile Time") +
  ggtitle("Mile Time By Engine") 
boxplot 

# Straight engine has relatively small qsec than V-shaped engine.
  1. Create a bar graph using ggplot, that shows the number of each carb type in mtcars.
carb <- ggplot(data = mtcars,aes(x = factor(mtcars$carb))) + 
  geom_bar()+
  xlab("Carb")+
  ylab("Count") +
  ggtitle("Number of Each Carb")
carb
## Warning: Use of `mtcars$carb` is discouraged. Use `carb` instead.

# among all the cars, there are small number of cars that have larger carburetors. 2 and 3 carburetors are the most common ones.
  1. Next show a stacked bar graph using ggplot of the number of each gear type and how they are further divided out by cyl.
library(ggplot2)

gear_cyl<- ggplot(data = mtcars,mapping = aes(x = factor(cyl), fill = factor(gear))) + 
  geom_bar()+
  xlab("Cyl")+
  ylab("Geary Type") +
  ggtitle("Number of Gear By Cyl")
gear_cyl

  1. Draw a scatter plot using ggplot showing the relationship between wt and mpg.
wt_mpg <- ggplot(data=mtcars, mapping = aes(x=wt, y=mpg)) +
  geom_point() +
   xlab("Weight")+
  ylab("Miles/Gallon") +
  ggtitle("Relationship between Weight and Miles/Gallon") +
  theme_classic()
wt_mpg # there seems to be a negative relationship between weight and miles/gallon.

  1. Design a visualization of your choice using ggplot using the data and write a brief summary about why you chose that visualization.
am_mpg <- ggplot(data = mtcars, mapping = aes(x=am, y=mpg)) + 
  geom_col(add = "mean")+
  xlab("Types of Transmission") +
  ylab("Avg Miles/Gallon") +
  ggtitle("Transmission VS mpg")
## Warning: Ignoring unknown parameters: add
am_mpg # Manual transmission has lower miles/gallon than automaic car.

Part 2 - Anscombe’s Quartet

  1. Anscombes quartet is a set of 4 \(x,y\) data sets that were published by Francis Anscombe in a 1973 paper Graphs in statistical analysis. For this first question load the anscombe data that is part of the library(datasets) in R. And assign that data to a new object called data.
library(datasets)
data <- datasets::anscombe
  1. Summarise the data by calculating the mean, variance, for each column and the correlation between each pair (eg. x1 and y1, x2 and y2, etc) (Hint: use the fBasics() package!)
library("fBasics")
## Loading required package: timeDate
## Loading required package: timeSeries
## 
## Attaching package: 'timeSeries'
## The following objects are masked from 'package:matrixStats':
## 
##     colCummaxs, colCummins, colCumprods, colCumsums, colMaxs, colMins,
##     colProds, colQuantiles, colSds, colVars, rowCumsums
## 
## Attaching package: 'fBasics'
## The following objects are masked from 'package:matrixStats':
## 
##     rowMaxs, rowMins, rowProds, rowQuantiles, rowSds, rowVars
colStats(data, FUN = mean)
##       x1       x2       x3       x4       y1       y2       y3       y4 
## 9.000000 9.000000 9.000000 9.000000 7.500909 7.500909 7.500000 7.500909
colStats(data, FUN = var)
##        x1        x2        x3        x4        y1        y2        y3        y4 
## 11.000000 11.000000 11.000000 11.000000  4.127269  4.127629  4.122620  4.123249
correlationTest(data$x1,data$y1,"pearson")
## 
## Title:
##  Pearson's Correlation Test
## 
## Test Results:
##   PARAMETER:
##     Degrees of Freedom: 9
##   SAMPLE ESTIMATES:
##     Correlation: 0.8164
##   STATISTIC:
##     t: 4.2415
##   P VALUE:
##     Alternative Two-Sided: 0.00217 
##     Alternative      Less: 0.9989 
##     Alternative   Greater: 0.001085 
##   CONFIDENCE INTERVAL:
##     Two-Sided: 0.4244, 0.9507
##          Less: -1, 0.9388
##       Greater: 0.5113, 1
## 
## Description:
##  Mon Aug  3 12:57:42 2020
correlationTest(data$x2,data$y2,"pearson")
## 
## Title:
##  Pearson's Correlation Test
## 
## Test Results:
##   PARAMETER:
##     Degrees of Freedom: 9
##   SAMPLE ESTIMATES:
##     Correlation: 0.8162
##   STATISTIC:
##     t: 4.2386
##   P VALUE:
##     Alternative Two-Sided: 0.002179 
##     Alternative      Less: 0.9989 
##     Alternative   Greater: 0.001089 
##   CONFIDENCE INTERVAL:
##     Two-Sided: 0.4239, 0.9506
##          Less: -1, 0.9387
##       Greater: 0.5109, 1
## 
## Description:
##  Mon Aug  3 12:57:42 2020
correlationTest(data$x3,data$y3,"pearson")
## 
## Title:
##  Pearson's Correlation Test
## 
## Test Results:
##   PARAMETER:
##     Degrees of Freedom: 9
##   SAMPLE ESTIMATES:
##     Correlation: 0.8163
##   STATISTIC:
##     t: 4.2394
##   P VALUE:
##     Alternative Two-Sided: 0.002176 
##     Alternative      Less: 0.9989 
##     Alternative   Greater: 0.001088 
##   CONFIDENCE INTERVAL:
##     Two-Sided: 0.4241, 0.9507
##          Less: -1, 0.9387
##       Greater: 0.511, 1
## 
## Description:
##  Mon Aug  3 12:57:42 2020
correlationTest(data$x4,data$y4,"pearson")
## 
## Title:
##  Pearson's Correlation Test
## 
## Test Results:
##   PARAMETER:
##     Degrees of Freedom: 9
##   SAMPLE ESTIMATES:
##     Correlation: 0.8165
##   STATISTIC:
##     t: 4.243
##   P VALUE:
##     Alternative Two-Sided: 0.002165 
##     Alternative      Less: 0.9989 
##     Alternative   Greater: 0.001082 
##   CONFIDENCE INTERVAL:
##     Two-Sided: 0.4246, 0.9507
##          Less: -1, 0.9388
##       Greater: 0.5115, 1
## 
## Description:
##  Mon Aug  3 12:57:42 2020
  1. Create scatter plots for each \(x, y\) pair of data.
xy1 <- ggplot(data=data, mapping = aes(x=x1, y=y1)) +
  geom_point() +
   xlab("x1")+
  ylab("y1") +
  ggtitle("Scatter plots for x1 and y1") +
  theme_classic()
xy1

xy2 <-ggplot(data=data, mapping = aes(x=x2, y=y2)) +
  geom_point() +
   xlab("x2")+
  ylab("y2") +
  ggtitle("Scatter plots for x2 and y2") +
  theme_classic()
xy2

xy3 <-ggplot(data=data, mapping = aes(x=x3, y=y3)) +
  geom_point() +
   xlab("x3")+
  ylab("y3") +
  ggtitle("Scatter plots for x3 and y3") +
  theme_classic()
xy3

xy4 <-ggplot(data=data, mapping = aes(x=x4, y=y4)) +
  geom_point() +
   xlab("x4")+
  ylab("y4") +
  ggtitle("Scatter plots for x4 and y4") +
  theme_classic()
xy4

  1. Now change the symbols on the scatter plots to solid circles and plot them together as a 4 panel graphic
#if(!require(devtools)) install.packages("devtools")
#devtools::install_github("kassambara/ggpubr")
library(ggpubr)
library(gridExtra)
library(cowplot)
## 
## ********************************************************
## Note: As of version 1.0.0, cowplot does not change the
##   default ggplot2 theme anymore. To recover the previous
##   behavior, execute:
##   theme_set(theme_cowplot())
## ********************************************************
## 
## Attaching package: 'cowplot'
## The following object is masked from 'package:ggpubr':
## 
##     get_legend
## The following object is masked from 'package:ggthemes':
## 
##     theme_map
ggarrange(xy1, xy2, xy3, xy4,ncol = 2, nrow = 2)

  1. Now fit a linear model to each data set using the lm() function.
lm1 <- lm(data$y1 ~ data$x1, data = data)
summary(lm1)
## 
## Call:
## lm(formula = data$y1 ~ data$x1, data = data)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1.92127 -0.45577 -0.04136  0.70941  1.83882 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)   
## (Intercept)   3.0001     1.1247   2.667  0.02573 * 
## data$x1       0.5001     0.1179   4.241  0.00217 **
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.237 on 9 degrees of freedom
## Multiple R-squared:  0.6665, Adjusted R-squared:  0.6295 
## F-statistic: 17.99 on 1 and 9 DF,  p-value: 0.00217
lm2 <- lm(data$y2 ~ data$x2, data = data)
summary(lm2)
## 
## Call:
## lm(formula = data$y2 ~ data$x2, data = data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -1.9009 -0.7609  0.1291  0.9491  1.2691 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)   
## (Intercept)    3.001      1.125   2.667  0.02576 * 
## data$x2        0.500      0.118   4.239  0.00218 **
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.237 on 9 degrees of freedom
## Multiple R-squared:  0.6662, Adjusted R-squared:  0.6292 
## F-statistic: 17.97 on 1 and 9 DF,  p-value: 0.002179
lm3 <- lm(data$y3 ~ data$x3, data = data)
summary(lm3)
## 
## Call:
## lm(formula = data$y3 ~ data$x3, data = data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -1.1586 -0.6146 -0.2303  0.1540  3.2411 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)   
## (Intercept)   3.0025     1.1245   2.670  0.02562 * 
## data$x3       0.4997     0.1179   4.239  0.00218 **
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.236 on 9 degrees of freedom
## Multiple R-squared:  0.6663, Adjusted R-squared:  0.6292 
## F-statistic: 17.97 on 1 and 9 DF,  p-value: 0.002176
lm4 <- lm(data$y4 ~ data$x4, data = data)
summary(lm4)
## 
## Call:
## lm(formula = data$y4 ~ data$x4, data = data)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -1.751 -0.831  0.000  0.809  1.839 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)   
## (Intercept)   3.0017     1.1239   2.671  0.02559 * 
## data$x4       0.4999     0.1178   4.243  0.00216 **
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.236 on 9 degrees of freedom
## Multiple R-squared:  0.6667, Adjusted R-squared:  0.6297 
## F-statistic:    18 on 1 and 9 DF,  p-value: 0.002165
  1. Now combine the last two tasks. Create a four panel scatter plot matrix that has both the data points and the regression lines. (hint: the model objects will carry over chunks!)
lm_xy1 <- ggplot(data=data, mapping = aes(x=x1, y=y1)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE)+
   xlab("x1")+
  ylab("y1") +
  ggtitle("Scatter plots for x1 and y1") +
  theme_classic()

lm_xy2 <-ggplot(data=data, mapping = aes(x=x2, y=y2)) +
  geom_point() +
    geom_smooth(method = "lm", se = FALSE)+
   xlab("x2")+
  ylab("y2") +
  ggtitle("Scatter plots for x2 and y2") +
  theme_classic()

lm_xy3 <-ggplot(data=data, mapping = aes(x=x3, y=y3)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE)+
  xlab("x3")+
  ylab("y3") +
  ggtitle("Scatter plots for x3 and y3") +
  theme_classic()

lm_xy4 <-ggplot(data=data, mapping = aes(x=x4, y=y4)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE)+
   xlab("x4")+
  ylab("y4") +
  ggtitle("Scatter plots for x4 and y4") +
  theme_classic()

ggarrange(lm_xy1, lm_xy2, lm_xy3, lm_xy4,ncol = 2, nrow = 2)
## `geom_smooth()` using formula 'y ~ x'
## `geom_smooth()` using formula 'y ~ x'
## `geom_smooth()` using formula 'y ~ x'
## `geom_smooth()` using formula 'y ~ x'

  1. Now compare the model fits for each model object.
# use Adjusted R^2 to compare the model fitpar
summary(lm1) # 0.6295 

Call: lm(formula = data\(y1 ~ data\)x1, data = data)

Residuals: Min 1Q Median 3Q Max -1.92127 -0.45577 -0.04136 0.70941 1.83882

Coefficients: Estimate Std. Error t value Pr(>|t|)
(Intercept) 3.0001 1.1247 2.667 0.02573 * data$x1 0.5001 0.1179 4.241 0.00217 ** — Signif. codes: 0 ‘’ 0.001 ’’ 0.01 ’’ 0.05 ‘.’ 0.1 ’ ’ 1

Residual standard error: 1.237 on 9 degrees of freedom Multiple R-squared: 0.6665, Adjusted R-squared: 0.6295 F-statistic: 17.99 on 1 and 9 DF, p-value: 0.00217

summary(lm2) #  0.6292 

Call: lm(formula = data\(y2 ~ data\)x2, data = data)

Residuals: Min 1Q Median 3Q Max -1.9009 -0.7609 0.1291 0.9491 1.2691

Coefficients: Estimate Std. Error t value Pr(>|t|)
(Intercept) 3.001 1.125 2.667 0.02576 * data$x2 0.500 0.118 4.239 0.00218 ** — Signif. codes: 0 ‘’ 0.001 ’’ 0.01 ’’ 0.05 ‘.’ 0.1 ’ ’ 1

Residual standard error: 1.237 on 9 degrees of freedom Multiple R-squared: 0.6662, Adjusted R-squared: 0.6292 F-statistic: 17.97 on 1 and 9 DF, p-value: 0.002179

summary(lm3) # 0.6292 

Call: lm(formula = data\(y3 ~ data\)x3, data = data)

Residuals: Min 1Q Median 3Q Max -1.1586 -0.6146 -0.2303 0.1540 3.2411

Coefficients: Estimate Std. Error t value Pr(>|t|)
(Intercept) 3.0025 1.1245 2.670 0.02562 * data$x3 0.4997 0.1179 4.239 0.00218 ** — Signif. codes: 0 ‘’ 0.001 ’’ 0.01 ’’ 0.05 ‘.’ 0.1 ’ ’ 1

Residual standard error: 1.236 on 9 degrees of freedom Multiple R-squared: 0.6663, Adjusted R-squared: 0.6292 F-statistic: 17.97 on 1 and 9 DF, p-value: 0.002176

summary(lm4) # 0.6297

Call: lm(formula = data\(y4 ~ data\)x4, data = data)

Residuals: Min 1Q Median 3Q Max -1.751 -0.831 0.000 0.809 1.839

Coefficients: Estimate Std. Error t value Pr(>|t|)
(Intercept) 3.0017 1.1239 2.671 0.02559 * data$x4 0.4999 0.1178 4.243 0.00216 ** — Signif. codes: 0 ‘’ 0.001 ’’ 0.01 ’’ 0.05 ‘.’ 0.1 ’ ’ 1

Residual standard error: 1.236 on 9 degrees of freedom Multiple R-squared: 0.6667, Adjusted R-squared: 0.6297 F-statistic: 18 on 1 and 9 DF, p-value: 0.002165

# it seems that the four models have quite similar model fit.
  1. In text, summarize the lesson of Anscombe’s Quartet and what it says about the value of data visualization. While the distribution of data sets are very different (we can justify it through data visualization), the descriptive statistics can be extremely identical. We can say that data visualization is very important in preprocessing and exploring the dataset.