Last updated: 2020-02-20

Checks: 6 1

Knit directory: MSTPsummerstatistics/

This reproducible R Markdown analysis was created with workflowr (version 1.5.0). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


The R Markdown is untracked by Git. To know which version of the R Markdown file created these results, you’ll want to first commit it to the Git repo. If you’re still working on the analysis, you can ignore this warning. When you’re finished, you can run wflow_publish to commit the R Markdown file and build the HTML.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20180927) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility. The version displayed above was the version of the Git repository at the time these results were generated.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .DS_Store
    Ignored:    .RData
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    analysis/.RData
    Ignored:    analysis/.Rhistory

Untracked files:
    Untracked:  analysis/dataviz.Rmd

Unstaged changes:
    Modified:   analysis/powerAnalyses.Rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


There are no past versions. Publish this analysis with wflow_publish() to start tracking its development.


Data visualization in many dimensions with ggplot2

Load data and libraries

library(ggplot2)
cars <- mtcars
?mtcars

Examine structure of data

These data contain 32 observations on cars across 11 different variables. Some of these variables (e.g. mpg) are numeric, while others (e.g. cyl) are factors. Notice that these data are in “tidy” format, meaning that:

  1. Each variable forms a column.

  2. Each observation forms a row.

  3. Each type of observational unit forms a table.

dim(cars)
[1] 32 11
head(cars)
                   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 showing 2 dimensions

Let’s examine the relationship between two variables, mpg and wt:

ggplot(data = cars) + #data layer
  geom_point(aes(x = wt, y = mpg)) #geom layer, aesthetics layer

Plot showing 3 dimensions

Now let’s color by cylinder number. What is important to take into account for the cylinder variable?

ggplot(data = cars) + #data layer
  geom_point(aes(x = wt, y = mpg, color = cyl)) #geom layer, aesthetics layer

ggplot(data = cars) + #data layer
  geom_point(aes(x = wt, y = mpg, size = factor(cyl))) #geom layer, aesthetics layer, color
Warning: Using size for a discrete variable is not advised.

ggplot(data = cars) + #data layer
  geom_point(aes(x = wt, y = mpg, shape = factor(cyl))) #geom layer, aesthetics layer, color

ggplot(data = cars) + #data layer
  geom_point(aes(x = wt, y = mpg, color = factor(cyl))) #geom layer, aesthetics layer, color

Plot showing 4 dimensions

What if we’re interested in the same plot as above, but separated by automatic vs manual transmissions?

ggplot(data = cars) + #data layer
  geom_point(aes(x = wt, y = mpg, color = factor(cyl))) + #geom layer, aesthetics layer, color
  facet_wrap(~factor(am)) #facet

#rename factor labels
cars$am <- as.factor(cars$am)
levels(cars$am) <- c("automatic", "manual")

ggplot(data = cars) + #data layer
  geom_point(aes(x = wt, y = mpg, color = factor(cyl))) + #geom layer, aesthetics layer, color
  facet_wrap(~am) #facet

Plot showing 5 dimensions

cars$vs <- as.factor(cars$vs)
levels(cars$vs) <- c("V-shaped engine", "straight engine")

ggplot(data = cars) + #data layer
  geom_point(aes(x = wt, y = mpg, color = factor(cyl))) + #geom layer, aesthetics layer, color
  facet_grid(vs~am) #facet

Gone too far?

ggplot(data = cars) + #data layer
  geom_point(aes(x = wt, y = mpg, color = factor(cyl), size = disp, shape = factor(gear))) + #geom layer, aesthetics layer, color
  facet_grid(vs~am)

Additional points

Adding labels

labeled_plot <- ggplot(data = cars) + #data layer
  geom_point(aes(x = wt, y = mpg, color = factor(cyl))) + #geom layer, aesthetics layer, color
  ggtitle("Relationship between mpg and weight \n in mtcars") + 
  xlab("weight (1000 lbs)") + 
  ylab("miles per gallon (mpg)") +
  labs(color = "Cylinder type")

labeled_plot

Choosing colors

cylinder_colors <- c("#035AA6", "#F2AE2E", "#F23D3D")

labeled_plot +
  scale_color_manual(values=cylinder_colors)

Reordering factors

cars$cyl <- factor(cars$cyl)
cars$cyl <- factor(cars$cyl, levels(cars$cyl)[c(3,2,1)])

ggplot(data = cars) + #data layer
  geom_point(aes(x = wt, y = mpg, color = cyl)) + #geom layer, aesthetics layer, color
  ggtitle("Relationship between mpg and weight \n in mtcars") + 
  xlab("weight (1000 lbs)") + 
  ylab("miles per gallon (mpg)") +
  labs(color = "Cylinder type") +
  scale_color_manual(values=cylinder_colors)

Adding statistics

Remember, we are working with the grammar of graphics so we can add as many geoms as we want/need to our plot!

labeled_plot + 
  geom_smooth(aes(x = wt, y = mpg, color = factor(cyl)), method = "lm", se = FALSE) #additional geoms inherit data and aesthetics from the predefined plot

#we can also define a new dataset for an additional geom
library(dplyr)

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
means <- cars %>% 
  group_by(cyl) %>% 
  summarise(mean.wt = mean(wt), mean.mpg = mean(mpg))
means
# A tibble: 3 x 3
  cyl   mean.wt mean.mpg
  <fct>   <dbl>    <dbl>
1 8        4.00     15.1
2 6        3.12     19.7
3 4        2.29     26.7
labeled_plot + 
  geom_point(data = means, aes(x = mean.wt, y = mean.mpg, color = cyl), size = 10, alpha = 0.5) +
  scale_color_manual(values=c(cylinder_colors))

Themes

library(ggthemes)
labeled_plot + 
  theme_fivethirtyeight()


sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.6

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggthemes_4.2.0 dplyr_0.8.4    ggplot2_3.2.1 

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.3       plyr_1.8.5       compiler_3.6.1   pillar_1.4.3    
 [5] later_1.0.0      git2r_0.26.1     workflowr_1.5.0  tools_3.6.1     
 [9] digest_0.6.23    evaluate_0.14    lifecycle_0.1.0  tibble_2.1.3    
[13] gtable_0.3.0     pkgconfig_2.0.3  rlang_0.4.4      cli_2.0.1       
[17] yaml_2.2.1       xfun_0.12        withr_2.1.2      stringr_1.4.0   
[21] knitr_1.26       vctrs_0.2.2      fs_1.3.1         rprojroot_1.3-2 
[25] grid_3.6.1       tidyselect_1.0.0 glue_1.3.1       R6_2.4.1        
[29] fansi_0.4.1      rmarkdown_1.18   reshape2_1.4.3   farver_2.0.3    
[33] purrr_0.3.3      magrittr_1.5     backports_1.1.5  scales_1.1.0    
[37] promises_1.1.0   htmltools_0.4.0  assertthat_0.2.1 colorspace_1.4-1
[41] httpuv_1.5.2     labeling_0.3     utf8_1.1.4       stringi_1.4.5   
[45] lazyeval_0.2.2   munsell_0.5.0    crayon_1.3.4