class: center, middle, inverse, title-slide .title[ # Data Viz with ggplot2 ] .author[ ### DSC365: Introduction to Data Science ] .date[ ### September 1, 2026 ] --- ### Announcements - Lab 1 due **tonight** - Start Lab 2 in class on Thursday + Due **next tuesday** - Will Discuss Mini-Project 1 on Thursday + Due **two weeks later, before class starts** - Quiz #1 + Last 30 Minutes next Thursday (September 10) + Quarto, ggplot2, dplyr --- <img src="images/ggplot2.png" alt="Cartoon diplaying building a visualization like an artist paints a painting." width="2356" style="display: block; margin: auto;" /> --- ### Why visualize? Our brain is good at processing large amounts of visual information quickly! Long lists of numbers, not so much. <br> **Useful at two point in Data Science Cycle** + Exploratory Data Analysis (EDA) + Communicating Information <img src="images/sun-pic.png" alt="The Hertzsprung-Russell Diagram displaying the relationshing between the brightness and and color of starts and how this relationship also shows the lifecycle of the star." width="70%" style="display: block; margin: auto;" /> --- class:primary ### Datasaurus Part 2: Summary Statistics <br> <br> |dataset | mean_x| mean_y| std_dev_x| std_dev_y| corr_x_y| |:--------|------:|------:|---------:|---------:|--------:| |away | 54.266| 47.835| 16.770| 26.940| -0.064| |bullseye | 54.269| 47.831| 16.769| 26.936| -0.069| |dino | 54.263| 47.832| 16.765| 26.935| -0.064| |dots | 54.260| 47.840| 16.768| 26.930| -0.060| |star | 54.267| 47.840| 16.769| 26.930| -0.063| |v_lines | 54.270| 47.837| 16.770| 26.938| -0.069| --- class:primary ### Datasaurus: Plots <img src="ggplot2-notes_files/figure-html/quartet-plots-1.png" alt="Visualization of scatterplots for six datasets from the datasaurus dozen dataset. Shows that while these datasets all have the same correlation coefficent, the plots show very different types of relationships." style="display: block; margin: auto;" /> --- ### Grammar of Graphics Grammar of Graphics: grammatical rules for creating perceivable graphs - [Developed by Leland Wilkison](https://link.springer.com/book/10.1007/0-387-28695-0) Instead of thinking about a limited set of graphs, think about graphical forms - Different types of graphs may appear completely distinct, but in actuality share many common elements By making different visual choices, you can use graphs to highlight different aspects of the same data. - For example, here are three ways of displaying the same data: <img src="ggplot2-notes_files/figure-html/plots-3-1.png" alt="Depiction of three different ways to display the same dataset about the frequency of diamond cut types. The first is a regular bar chart, the second is a filled bar chart and the last is a pie chart." /> --- ### ggplot Based on The Grammar of Graphics where the components are independent, meaning we can generally change a component in isolation [(source)](https://www.tandfonline.com/doi/epdf/10.1198/jcgs.2009.07098?needAccess=true). .pull-left[ <img src="images/ggplot-hex.png" alt="Hex logo for ggplot2 package." width="40%" style="display: block; margin: auto;" /> ].pull-right[ <img src="images/template.png" alt="Code template to create a plot using the ggplot function." width="100%" style="display: block; margin: auto;" /> ] <br> <br> <br> <br> <br> [Help Information](https://rstudio.github.io/cheatsheets/html/data-visualization.html) --- ### ggplot 2: specifications A plot consists of several mostly independent specifications: 1. **aesthetics** - links between data variables and graphical features (position, color, shape, size) 2. **geometries** - geometric elements (points, lines, rectangles, text,...) 3. **scales** - scales map values in data space values in the aesthetic space. Scales change the coordinate space of an aesthetic, but don't change the underlying value (change at visual level, not mathematical) 4. **coordinate system** 5. **statistics**: mean, quantiles, etc 6. **faceting** - facets allow you to split plot by other variables to produce many sub-plots 7. **theme** - formating items, such as background color, fonts, margins... <br> <br> **Limitation**: tells us what words make up our graphical “sentences,” but offers no advice on how to write well --- ### Let's Build a Graph! ``` r library(tidyverse) head(diamonds) ``` ``` ## # A tibble: 6 × 10 ## carat cut color clarity depth table price x y z ## <dbl> <ord> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl> ## 1 0.23 Ideal E SI2 61.5 55 326 3.95 3.98 2.43 ## 2 0.21 Premium E SI1 59.8 61 326 3.89 3.84 2.31 ## 3 0.23 Good E VS1 56.9 65 327 4.05 4.07 2.31 ## 4 0.29 Premium I VS2 62.4 58 334 4.2 4.23 2.63 ## 5 0.31 Good J SI2 63.3 58 335 4.34 4.35 2.75 ## 6 0.24 Very Good J VVS2 62.8 57 336 3.94 3.96 2.48 ``` --- ### Plot Plan <img src="images/plot-plan.png" alt="Visualization relating variables in a dataset to its correpsonding components on a plot." width="100%" style="display: block; margin: auto;" /> --- ### We Begin with the Data ``` r *ggplot(data=diamonds) ``` <img src="ggplot2-notes_files/figure-html/unnamed-chunk-8-1.png" alt="Visualization of the gray plot background that is the default for ggplot. Happens when only call in the dataset but no specific variables." /> --- ### Then we specify the aesthetic mappings ``` r *ggplot(data=diamonds, aes(x=carat, y = price)) ``` <img src="ggplot2-notes_files/figure-html/unnamed-chunk-9-1.png" alt="Builds on previous picture, where we now have added our two variables to the gpplot code. The appropriate axes labels now appear." /> --- ### Then we choose a geom ``` r ggplot(data=diamonds, aes(x=carat, y = price)) + * geom_point() ``` <img src="ggplot2-notes_files/figure-html/unnamed-chunk-11-1.png" alt="Builds on previous picture where we have now added a geometry, a point. So now a point is diplayed for each observation." /> --- ### We can then add an aesthetic ``` r ggplot(data = diamonds, aes(x = carat, y = price)) + * geom_point(aes(colour = cut)) ``` <img src="ggplot2-notes_files/figure-html/unnamed-chunk-13-1.png" alt="Identical to previous plot, except now each point is colored by the cut of the diamond for that observation." /> --- ### And add another layer ``` r ggplot(data = diamonds, aes(x = carat, y = price)) + geom_point(aes(colour = cut)) + * geom_smooth() ``` ``` ## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")' ``` <img src="ggplot2-notes_files/figure-html/unnamed-chunk-15-1.png" alt="Identical to previous plot, except now we have added a line that summarises the relationship between carat and price." /> --- ### Mapping aesthetics vs setting aesthetics ``` r ggplot(data = diamonds, aes(x = carat, y = price) + * geom_point(aes(colour = cut), size = 2, alpha = .5) + * geom_smooth(aes(fill = cut), colour = "lightgrey") ``` ``` ## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")' ``` <img src="ggplot2-notes_files/figure-html/unnamed-chunk-17-1.png" alt="Now instead of one line depicting the overall relationhip there are now five lines, one for each of the diamond cuts." /> --- ### Facet ``` r ggplot(data = diamonds, aes(x = carat, y = price)) + geom_point(aes(colour = cut), size = 2, alpha = .5) + geom_smooth(aes(fill = cut), colour = "lightgrey") + * facet_wrap(~cut) ``` ``` ## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")' ``` <img src="ggplot2-notes_files/figure-html/unnamed-chunk-19-1.png" alt="Instead of maintaing all of this information on one plot, now we have broken out the data into five faceted plots, one for each cut, so now we can more easily visualize the relationship between carat and price for each diamond type." /> --- ### What Type of Chart to Use? - What type of variables are you working with? Numerical? Categorical? - Number of observations? - Important moderating variables? - Use of small multiples? <br> [The R Graph Gallery](https://r-graph-gallery.com) --- ### Later: Graphical Perception To visually display data, information is encoded into a graph. The viewer then visually decodes this information, known as graphical perception, to gain knowledge. A successful graphic allows the user to perform graphical perception accurately and efficiently After we have chosen the appropriate plot to visualize the data, focus on these two principles: - Keep it simple - Show the data clearly <br> But for now, let's move to the .qmd document