class: center, middle, inverse, title-slide .title[ # Data Literacy: Introduction to R ] .subtitle[ ## Data Visualization ] .author[ ### Veronika Batzdorfer ] .date[ ### 2025-11-21 ] --- layout: true --- ## We'll start rather basic <img src="data:image/png;base64,#https://github.com/jobreu/r-intro-gesis-2021/blob/main/content/img/trump.jpg?raw=true" width="85%" style="display: block; margin: auto;" /> .footnote[https://twitter.com/katjaberlin/status/1290667772779913218] --- ## Content of the visualization sessions .pull-left[ **`Base R` visualization** - Standard plotting procedures in R - very short ] .pull-right[ **`tidyverse`/`ggplot2` visualization** - Modern interface to graphics - grammar of graphics ] --- ### Data for this session ``` r library(palmerpenguins) library(tidyverse) library(ggbeeswarm) df <- penguins %>% drop_na() ``` --- ## Graphics in `R` The `graphics` package is already included. .pull-left[ ``` r #-- Adjust plot margins-- # Create summary data first spec_counts <- df %>% count(species) %>% arrange(desc(n)) par(mar = c(5, 4, 4, 2)) barplot( height = spec_counts$n, names.arg = spec_counts$species, las = 2, main = "Penguin Species Count", ylab = "Number of Records", col = c("darkorange", "purple", "cyan4"), cex.names = 0.9 ) ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-2-1.png" style="display: block; margin: auto;" /> ] --- ## Let's start from the beginning The most basic function to plot in R is `plot()`. .pull-left[ ``` r plot(df$bill_length_mm, df$flipper_length_mm, main = "Bill vs. Flipper Length", xlab = "Bill Length (mm)", ylab = "Flipper Length (mm)", col = "darkblue", pch = 19) ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-3-1.png" style="display: block; margin: auto;" /> ] --- ## Where to go from here with `base R` graphics? .pull-left[ Using similar procedures, we can add more and more stuff to our plot or edit its elements: - regression lines - legends - annotations - colors - etc. ] .pull-right[ We can also create different *plot types*, such as - histograms - barplots - boxplots - densities - pie charts - etc. ] --- ## Example: A simple boxplot .pull-left[ ``` r boxplot( df$body_mass_g ~ df$year ) ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-4-1.png" style="display: block; margin: auto;" /> ] --- ## The `par()` and `dev.off()` functions for plots .highlight[`par()`] stands for graphical parameters and is called before the actual plotting function. It prepares the graphics device in `R`. The most commonly used options are for "telling" the device that 2, 3, 4, or `x` plots have to be printed. We can, e.g., use `mfrow` for specifying how many rows (the first value in the vector) and columns (the second value in the vector) we aim to plot. ``` r par(mfrow = c(2, 2)) ``` One caveat of using this function is that we actively have to turn off the device before generating another independent plot. ``` r dev.off() ``` --- ## Exporting with *RStudio* <img src="data:image/png;base64,#https://github.com/jobreu/r-intro-gesis-2021/blob/main/content/img/saveGraphic.PNG?raw=true" style="display: block; margin: auto;" /> --- ## Saving plots via a command Alternatively, you can also export plots with the commands `png()`, `pdf()` or `jpeg()`, for example. For this purpose, you first have to wrap the plot call between one of those functions and a `dev.off()`call. ``` r png("Plot.png") hist(df$body_mass_g) dev.off() ``` ``` r pdf("Plot.pdf") hist(df$body_mass_g) dev.off() ``` ``` r jpeg("Plot.jpeg") hist(df$body_mass_g) dev.off() ``` --- ## What is `ggplot2`? `ggplot2` is another `R` package for creating plots and is part of the `tidyverse`. It uses the *grammar of graphics*. Some things to note about `ggplot2`: - it is well-suited for multi-dimensional data - it expects data (frames) as input - components of the plot are added as layers ``` r plot_call + layer_1 + layer_2 + ... + layer_n ``` --- ## Barplots as in `base R` .tinyish[ .pull-left[ ``` r ggplot(df, aes(x = fct_infreq(species))) + geom_bar(fill = c("darkorange", "purple", "cyan4")) + labs( title = "Penguin Species Count", y = "Number of Records", x = NULL ) ``` ] ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-11-1.png" style="display: block; margin: auto;" /> ] --- ## Boxplots as in `base R` .tinyish[ .pull-left[ ``` r ggplot(df, aes(x = factor(year), y = body_mass_g)) + geom_boxplot() ``` ] ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-12-1.png" style="display: block; margin: auto;" /> ] --- ## Components of a plot According to Wickham (2010, 8)* a layered plot consists of the following components: <span class="footnote"> <small><small><span class="red bold">*</span> http://dx.doi.org/10.1198/jcgs.2009.07098</small></small> </span> - data and aesthetic mappings, - geometric objects, - scales, - and facet specification ``` r plot_call + data + aesthetics + geometries + scales + facets ``` --- ## Data requirements You can use one single data frame to create a plot in `ggplot2`. This creates a smooth workflow from data wrangling to the final presentation of the results. <br> <img src="data:image/png;base64,#https://github.com/jobreu/r-intro-gesis-2021/blob/main/content/img/data-science_man.png?raw=true" width="65%" style="display: block; margin: auto;" /> <small><small>Source: http://r4ds.had.co.nz</small></small> --- ## Why the long format? 🐴 `ggplot2` prefers data in long format (**NB**: of course, only if this is possible and makes sense for the data set at hand) .pull-left[ - every element we aim to plot is an observation - no thinking required how a specific variable relates to an observation - most importantly, the long format is more parsimonious - it requires less memory and less disk space ] .pull-right[ <img src="data:image/png;base64,#https://github.com/jobreu/r-intro-gesis-2021/blob/main/content/img/long.png?raw=true" width="40%" style="display: block; margin: auto;" /> <small><small>Source: https://github.com/gadenbuie/tidyexplain#tidy-data</small></small> ] --- ## Before we start The architecture of building plots in `ggplot` is similar to standard `R` graphics. There is an initial plotting call, and subsequently, more stuff is added to the plot. However, in `base R`, it is sometimes tricky to find out how to add (or remove) certain plot elements. For example, think of removing the axis ticks in the scatter plot. We will systematically explore which elements are used in `ggplot` in this session. --- ## Creating your own plot We do not want to give a lecture on the theory behind data visualization (if you want that, we suggest having a look at the excellent book [*Fundamentals of Data Visualization*](https://serialmentor.com/dataviz/) by Claus O. Wilke). Three components are important: - Plot initiation and data input - aesthetics definition - so-called geoms --- ## Plot initiation Now, let's start from the beginning and have a closer look at the *grammar of graphics*. .pull-left[ `ggplot()` is the most basic command to create a plot: ``` r ggplot() ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-13-1.png" style="display: block; margin: auto;" /> ] **But it doesn't show anything...** --- ## What now? Data input! .pull-left[ ``` r ggplot(data = df ) ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-14-1.png" style="display: block; margin: auto;" /> ] **Still nothing there...** --- ## `aes`thetics! .pull-left[ `ggplot` requires information about the variables to plot. ``` r ggplot(data = df, aes(x = bill_length_mm, y = flipper_length_mm)) ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-15-1.png" style="display: block; margin: auto;" /> ] **That's a little bit better, right?** --- ## `geom`s! .pull-left[ Finally, `ggplot` needs information *how* to plot the variables. ``` r ggplot(data = df, aes(x = bill_length_mm, y = flipper_length_mm)) + geom_point(aes(color = species)) ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-16-1.png" style="display: block; margin: auto;" /> ] **A scatter plot!** --- ## Add a fancy `geom` .pull-left[ We can also add more than one `geom`. ``` r ggplot(data = df, aes(x = bill_length_mm, y = flipper_length_mm)) + geom_point(aes(color = species))+ geom_smooth(method = "lm", se = FALSE) ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-17-1.png" style="display: block; margin: auto;" /> ] **A regression line!** (without confidence intervals; the regression behind this operation is run automatically) --- ## Going further: adding group `aes`thetics .pull-left[ We can add different colors for different groups in our data. ``` r ggplot(data = df, aes(x = bill_length_mm, y = flipper_length_mm, group = species)) + geom_point(aes(color = species))+ geom_smooth(method = "lm", se = FALSE) ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-18-1.png" style="display: block; margin: auto;" /> ] --- ## Manipulating group `aes`thetics .pull-left[ We can also change the colors that are used in the plot. ``` r ggplot(data = df, aes(x = bill_length_mm, y = flipper_length_mm, group = species, color=species)) + geom_point(aes(color = species))+ geom_smooth(method = "lm", se = FALSE) ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-19-1.png" style="display: block; margin: auto;" /> ] The legend is drawn automatically, that's handy! --- ## Using another color palette .pull-left[ ``` r ggplot(data = df, aes(x = bill_length_mm, y = flipper_length_mm, group = species, color=species)) + geom_point(aes(color = species))+ geom_smooth(method = "lm", se = FALSE)+ scale_color_brewer( palette = "Dark2" ) ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-20-1.png" style="display: block; margin: auto;" /> ] --- ## Difference between `color` and `fill` Notably, there are two components of the plot or `geom` associated with colors: `color` and `fill`. Generally, .highlight[`color`] refers to the geometry borders, such as a line. .highlight[`fill`] refers to a geometry area, such as a polygon. Remember when using `scale_color_brewer` or `scale_fill_brewer` in your plots. --- ## Colors and `theme`s One particular strength of `ggplot2` lies in its immense theming capabilities. The package has some built-in theme functions that makes theming a plot fairly easy, e.g., - `theme_bw()` - `theme_apa()` - `theme_void()` - etc. See: https://ggplot2.tidyverse.org/reference/ggtheme.html --- ## Alternative to being too colorful: facets .pull-left[ ``` r ggplot(data = df, aes(x = bill_length_mm, y = flipper_length_mm, group = species, color=species)) + geom_smooth( color = "black", method = "lm", se = FALSE ) + facet_wrap(~species, ncol = 3, nrow=2) + papaja::theme_apa() ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-21-1.png" style="display: block; margin: auto;" /> ] --- ## The `theme()` argument in general The most direct interface for manipulating your theme is the `theme()` argument. Here you can change the appearance of: - axis labels - captions and titles - legend - grid layout - the wrapping strips - ... --- ## Example: changing the grid layout & axis labels .pull-left[ ``` r ggplot(data = df, aes(x = bill_length_mm, y = flipper_length_mm, group = species, color=species)) + geom_smooth( color = "black", method = "lm", se = FALSE ) + facet_wrap(~species, ncol = 3, nrow=2) + theme_bw()+ theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank(), strip.background = element_rect(fill = "white") ) ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-22-1.png" style="display: block; margin: auto;" /> ] --- ## Example: changing axis labels .pull-left[ ``` r ggplot(data = df, aes(x = bill_length_mm, y = flipper_length_mm, group = species, color=species)) + geom_smooth( color = "black", method = "lm", se = FALSE ) + facet_wrap(~species, ncol = 3, nrow=2) + theme_bw()+ theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank(), strip.background = element_rect(fill = "white") ) + ylab("Flossenlänge [mm]") + xlab("Schnabellänge [mm]") ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-23-1.png" style="display: block; margin: auto;" /> ] --- ## A note on plotting options .pull-left[ Working with combined aesthetics and different data inputs can become challenging. Particularly, plotting similar aesthetics which interfere with the automatic procedures can create conflicts. Some 'favorites' include: - Multiple legends - and various color scales for similar `geoms` ] .pull-right[ <img src="data:image/png;base64,#https://github.com/jobreu/r-intro-gesis-2021/blob/main/content/img/800px-The_Scream.jpg?raw=true" style="display: block; margin: auto;" /> ] .right[ <small><small>Source: https://de.wikipedia.org/wiki/Der_Schrei#/media/File:The_Scream.jpg</small></small> ] --- ## `ggplot` plots are 'simple' objects In contrast to standard `R` plots, `ggplot2` outputs are standard objects like any other object in `R` (they are lists). So there is no graphics device involved from which we have to record our plot to re-use it later. We can just use it directly. ``` r my_fancy_plot <- ggplot(df, aes(x = bill_length_mm, y = flipper_length_mm, color = species)) + geom_point() my_fancy_plot <- my_fancy_plot + geom_smooth() ``` Additionally, there is also no need to call `dev.off()` --- ## It makes combining plots easy As of today, there are now a lot of packages that help to combine `ggplot2`s fairly easily. For example, the [`cowplot` package](https://cran.r-project.org/web/packages/cowplot/index.html) provides a really flexible framework. Yet, fiddling with this package can become quite complicated. A very easy-to-use package for combining `ggplot`s is [`patchwork` package](https://cran.r-project.org/web/packages/patchwork/index.html). --- ## Plotting side by side in one row .pull-left[ ``` r library(patchwork) p_hist <- ggplot(df, aes(x = body_mass_g)) + geom_histogram() p_box <- ggplot(df, aes(y = body_mass_g)) + geom_boxplot() p_density <- ggplot(df, aes(x = body_mass_g)) + geom_density() (p_hist | p_box | p_density) + plot_layout(ncol = 3) + plot_annotation(title = "Body Mass: Three Views") ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-25-1.png" style="display: block; margin: auto;" /> ] --- ## Plotting in two columns .pull-left[ ``` r p_hist / p_box ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-26-1.png" style="display: block; margin: auto;" /> ] --- ## There's more You can also annotate plots with titles, subtitles, captions, and tags. You can nest plots and introduce more complex layouts. If you're interested in this, you should check out the [`patchwork` repository on *GitHub*](https://github.com/thomasp85/patchwork) as everything is really well-documented there. --- ## Exporting ggplot graphics Exporting `ggplot2` graphics is fairly easy with the `ggsave()` function. It automatically detects the file format. You can also define the plot height, width, and dpi, which is particularly useful to produce high-class graphics for publications. ``` r ggsave("nice_plot.png", p_hist, dpi = 300) ``` Or: ``` r ggsave("nice_plot.tiff", p_hist, dpi = 300) ``` --- ## Visual exploratory data analysis .pull-left[ ``` r library(visdat) vis_miss(df [,1:5]) ``` ] .pull-right[ <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-29-1.png" style="display: block; margin: auto;" /> ] --- ## Exploratory Analyses ``` r # --- STEP 1: Foundation --- explanatory_plot <- df %>% # Focus on the core relationship ggplot(aes(x = bill_length_mm, y = flipper_length_mm, color = species)) + # --- STEP 2: Add uncertainty --- geom_smooth( method = "lm", se = TRUE, # confidence bands alpha = 0.1, # Transparency size = 1 ) + # --- STEP 3: Raw data distribution --- geom_beeswarm( aes(size = body_mass_g), # Encode third dimension alpha = 0.6, dodge.width = 0.5 # Separate by species ) + # --- STEP 4: Highlight key insights --- geom_hline( yintercept = 200, linetype = "dashed", color = "gray30" ) + annotate( "text", x = 45, y = 205, label = "Critical Flipper Length", size = 3.5, color = "gray30", fontface = "italic" ) ``` --- ``` r # --- STEP 5: Polish scales --- explanatory_plot <- explanatory_plot + # color palette (colorblind safe) scale_color_manual( values = c("Adelie" = "#0072B2", "Chinstrap" = "#E79F00", "Gentoo" = "#009E73") ) + scale_size_continuous(range = c(1.5, 5)) + # --- STEP 6: Facet by island --- facet_wrap(~ island, ncol = 1) + # --- STEP 7: Custom theme --- theme_bw(base_size = 12) + theme( legend.position = "top", plot.title = element_text(face = "bold", size = 16, margin = margin(b = 10)), strip.background = element_rect(fill = "#F0F0F0", color = NA), panel.border = element_rect(color = "gray80", fill = NA), axis.title = element_text(face = "bold") ) + # --- STEP 8: Clear labels --- labs( title = "Bill-Flipper Relationship Across Penguin Species & Islands", subtitle = "Point size represents body mass | Shaded areas show 95% CI", x = "Bill Length (mm)", y = "Flipper Length (mm)", color = "Species", size = "Body Mass (g)", caption = "Data: Palmer Penguins" ) ``` --- ``` r explanatory_plot ``` <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-31-1.png" width="50%" style="display: block; margin: auto;" /> --- ## Which species differ and how much? ``` r library(ggsignif) library(ggrepel) difference_plot <-ggplot(df, aes(x = species, y = body_mass_g, fill = species)) + geom_violin(alpha = 0.4) + geom_boxplot(width = 0.1, fill = "white", alpha = 0.8) + # STATISTICAL ANNOTATION ggsignif::geom_signif( comparisons = list(c("Adelie", "Chinstrap"), c("Chinstrap", "Gentoo")), map_signif_level = TRUE, textsize = 3 ) + # REFERENCE LINE geom_hline(yintercept = 5000, linetype = "dashed", color = "gray50") + annotate("text", x = 2.5, y = 5200, label = "Conservation Threshold", color = "gray50", size = 3) + scale_fill_brewer(palette = "Set2") + theme(legend.position = "none") + labs(title = "Species Body Mass with Statistical Comparisons") ``` --- ## Which species differ and how much? ``` r difference_plot ``` <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-32-1.png" width="50%" style="display: block; margin: auto;" /> --- ## Excercise # 10 min. - Create violin plots of `bill_length_mm` by **island**. - Add significance brackets `comparing Biscoe` vs. `Dream islands` and `Dream` vs. `Torgersen`. - Use a colorblind-friendly palette and remove the legend. --- ``` r # SOLUTION violin_plot <- ggplot(df, aes(x = island, y = bill_length_mm, fill = island)) + geom_violin(alpha = 0.5) + geom_boxplot(width = 0.1, fill = "white") + ggsignif::geom_signif( comparisons = list(c("Biscoe", "Dream"), c("Dream", "Torgersen")), map_signif_level = TRUE ) + scale_fill_brewer(palette = "Set2") + theme_minimal() + labs( title = "Bill Length Variation Across Islands", subtitle = "Violins show distribution; boxes show quartiles", x = "Island", y = "Bill Length (mm)" ) + theme(legend.position = "none") ``` --- ``` r violin_plot ``` <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-33-1.png" width="50%" style="display: block; margin: auto;" /> --- ## Exercise II # 10 min. - Make a scatter plot: `bill_length_mm` vs. `flipper_length_mm` (colored by species). - Label the 5 penguins with highest body mass with their actual mass values. - Add a vertical reference line at the mean bill length and label it. - Use theme_bw() and professional labels. --- ## Solution ``` r top_5 <- df %>% slice_max(order_by = body_mass_g, n = 5) # Calculate ref mean_bill <- mean(df$bill_length_mm) scatterplot <- ggplot(df, aes(x = bill_length_mm, y = flipper_length_mm, color = species)) + geom_point(alpha = 0.6, size = 2) + # DATA LABELS for outliers geom_label_repel( data = top_5, aes(label = round(body_mass_g)), # Round for clean labels nudge_x = 0.5, min.segment.length = 0, size = 3 ) + # REFERENCE LINE + annotation geom_vline(xintercept = mean_bill, linetype = "dashed", color = "gray50") + annotate("text", x = mean_bill + 2, y = 225, label = paste("Mean:", round(mean_bill, 1), "mm"), color = "gray50", size = 3, hjust = 0) + scale_color_brewer(palette = "Dark2") + theme_bw(base_size = 12) + labs( title = "Penguin Measurements with Outlier Highlights", subtitle = "Labels show body mass (g) for 5 heaviest individuals", x = "Bill Length (mm)", y = "Flipper Length (mm)", color = "Species" ) ``` --- ``` r scatterplot ``` <img src="data:image/png;base64,#3_2_Data_Visualization_Part_1_files/figure-html/unnamed-chunk-34-1.png" width="60%" style="display: block; margin: auto;" /> --- ## Some additional resources - [ggplot2 - Elegant Graphics for Data Analysis](https://www.springer.com/gp/book/9783319242750) by Hadley Wickham - [Chapter 3](https://r4ds.had.co.nz/data-visualisation.html) in *R for Data Science* - [Fundamentals of Data Visualization](https://serialmentor.com/dataviz/) by Claus O. Wilke - [Data Visualization - A Practical Introduction](https://press.princeton.edu/titles/13826.html) by Kieran Healy - [data-to-viz](https://www.data-to-viz.com/) - [R Graph Gallery](https://www.r-graph-gallery.com/) - [BBC Visual and Data Journalism cookbook for R graphics](https://bbc.github.io/rcookbook/#how_to_create_bbc_style_graphics) - [List of `ggplot2` extensions](https://exts.ggplot2.tidyverse.org/)