r4ds/oreilly/data-visualize.html

621 lines
55 KiB
HTML
Raw Normal View History

<section data-type="chapter" id="chp-data-visualize">
2023-01-13 07:22:57 +08:00
<h1><span id="sec-data-visualization" class="quarto-section-identifier d-none d-lg-block"><span class="chapter-title">Data visualization</span></span></h1>
<section id="data-visualize-introduction" data-type="sect1">
<h1>
Introduction</h1>
<blockquote class="blockquote">
<p>“The simple graph has brought more information to the data analysts mind than any other device.” — John Tukey</p>
</blockquote>
2023-01-13 07:22:57 +08:00
<p>R has several systems for making graphs, but ggplot2 is one of the most elegant and most versatile. ggplot2 implements the <strong>grammar of graphics</strong>, a coherent system for describing and building graphs. With ggplot2, you can do more and faster by learning one system and applying it in many places.</p>
<p>This chapter will teach you how to visualize your data using <strong>ggplot2</strong>. We will start by creating a simple scatterplot and use that to introduce aesthetic mappings and geometric objects the fundamental building blocks of ggplot2. We will then walk you through visualizing distributions of single variables as well as visualizing relationships between two or more variables. Well finish off with saving your plots and troubleshooting tips.</p>
<section id="data-visualize-prerequisites" data-type="sect2">
<h2>
Prerequisites</h2>
<p>This chapter focuses on ggplot2, one of the core packages in the tidyverse. To access the datasets, help pages, and functions used in this chapter, load the tidyverse by running:</p>
<div class="cell">
2022-11-19 01:26:25 +08:00
<pre data-type="programlisting" data-code-language="r">library(tidyverse)
2023-01-13 07:22:57 +08:00
#&gt; ── Attaching core tidyverse packages ──────────────── tidyverse 1.3.2.9000 ──
#&gt; ✔ dplyr 1.0.99.9000 ✔ readr 2.1.3
#&gt; ✔ forcats 0.5.2 ✔ stringr 1.5.0
2023-01-13 07:22:57 +08:00
#&gt; ✔ ggplot2 3.4.0.9000 ✔ tibble 3.1.8
#&gt; ✔ lubridate 1.9.0 ✔ tidyr 1.3.0
2023-01-13 07:22:57 +08:00
#&gt; ✔ purrr 1.0.1
#&gt; ── Conflicts ─────────────────────────────────────── tidyverse_conflicts() ──
#&gt; ✖ dplyr::filter() masks stats::filter()
2023-01-13 07:22:57 +08:00
#&gt; ✖ dplyr::lag() masks stats::lag()
#&gt; Use the conflicted package (&lt;http://conflicted.r-lib.org/&gt;) to force all conflicts to become errors</pre>
</div>
<p>That one line of code loads the core tidyverse; the packages that you will use in almost every data analysis. It also tells you which functions from the tidyverse conflict with functions in base R (or from other packages you might have loaded)<span data-type="footnote">You can eliminate that message and force conflict resolution to happen on demand by using the conflicted package, which becomes more important as you load more packages. You can learn more about conflicted at <a href="https://conflicted.r-lib.org" class="uri">https://conflicted.r-lib.org</a>.</span>.</p>
2023-01-13 07:22:57 +08:00
<p>If you run this code and get the error message <code>there is no package called 'tidyverse'</code>, youll need to first install it, then run <code><a href="https://rdrr.io/r/base/library.html">library()</a></code> once again.</p>
<div class="cell">
2022-11-19 01:26:25 +08:00
<pre data-type="programlisting" data-code-language="r">install.packages("tidyverse")
library(tidyverse)</pre>
</div>
<p>You only need to install a package once, but you need to load it every time you start a new session.</p>
2023-01-13 07:22:57 +08:00
<p>In addition to tidyverse, we will also use the <strong>palmerpenguins</strong> package, which includes the <code>penguins</code> dataset containing body measurements for penguins on three islands in the Palmer Archipelago.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">library(palmerpenguins)</pre>
</div>
</section>
</section>
<section id="first-steps" data-type="sect1">
<h1>
First steps</h1>
2023-01-13 07:22:57 +08:00
<p>Lets use our first graph to answer a question: Do penguins with longer flippers weigh more or less than penguins with shorter flippers? You probably already have an answer, but try to make your answer precise. What does the relationship between flipper length and body mass look like? Is it positive? Negative? Linear? Nonlinear? Does the relationship vary by the species of the penguin? And how about by the island where the penguin lives.</p>
2023-01-13 07:22:57 +08:00
<section id="the-penguins-data-frame" data-type="sect2">
<h2>
The penguins data frame</h2>
2023-01-13 07:22:57 +08:00
<p>You can test your answer with the <code>penguins</code> <strong>data frame</strong> found in palmerpenguins (a.k.a. <code><a href="https://allisonhorst.github.io/palmerpenguins/reference/penguins.html">palmerpenguins::penguins</a></code>). A data frame is a rectangular collection of variables (in the columns) and observations (in the rows). <code>penguins</code> contains 344 observations collected and made available by Dr. Kristen Gorman and the Palmer Station, Antarctica LTER<span data-type="footnote">Horst AM, Hill AP, Gorman KB (2020). palmerpenguins: Palmer Archipelago (Antarctica) penguin data. R package version 0.1.0. <a href="https://allisonhorst.github.io/palmerpenguins/" class="uri">https://allisonhorst.github.io/palmerpenguins/</a>. doi: 10.5281/zenodo.3960218.</span>.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">penguins
#&gt; # A tibble: 344 × 8
#&gt; species island bill_length_mm bill_depth_mm flipper_length_mm
#&gt; &lt;fct&gt; &lt;fct&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;int&gt;
#&gt; 1 Adelie Torgersen 39.1 18.7 181
#&gt; 2 Adelie Torgersen 39.5 17.4 186
#&gt; 3 Adelie Torgersen 40.3 18 195
#&gt; 4 Adelie Torgersen NA NA NA
#&gt; 5 Adelie Torgersen 36.7 19.3 193
#&gt; 6 Adelie Torgersen 39.3 20.6 190
#&gt; # … with 338 more rows, and 3 more variables: body_mass_g &lt;int&gt;, sex &lt;fct&gt;,
#&gt; # year &lt;int&gt;</pre>
2023-01-13 07:22:57 +08:00
</div>
<p>This data frame contains 8 columns. For an alternative view, where you can see all variables and the first few observations of each variable, use <code><a href="https://pillar.r-lib.org/reference/glimpse.html">glimpse()</a></code>. Or, if youre in RStudio, run <code>View(penguins)</code> to open an interactive data viewer.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">glimpse(penguins)
#&gt; Rows: 344
#&gt; Columns: 8
#&gt; $ species &lt;fct&gt; Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, A…
#&gt; $ island &lt;fct&gt; Torgersen, Torgersen, Torgersen, Torgersen, Torge…
#&gt; $ bill_length_mm &lt;dbl&gt; 39.1, 39.5, 40.3, NA, 36.7, 39.3, 38.9, 39.2, 34.…
#&gt; $ bill_depth_mm &lt;dbl&gt; 18.7, 17.4, 18.0, NA, 19.3, 20.6, 17.8, 19.6, 18.…
#&gt; $ flipper_length_mm &lt;int&gt; 181, 186, 195, NA, 193, 190, 181, 195, 193, 190, …
#&gt; $ body_mass_g &lt;int&gt; 3750, 3800, 3250, NA, 3450, 3650, 3625, 4675, 347…
#&gt; $ sex &lt;fct&gt; male, female, female, NA, female, male, female, m…
#&gt; $ year &lt;int&gt; 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2…</pre>
</div>
<p>Among the variables in <code>penguins</code> are:</p>
<ol type="1"><li><p><code>species</code>: a penguins species (Adelie, Chinstrap, or Gentoo).</p></li>
<li><p><code>flipper_length_mm</code>: length of a penguins flipper, in millimeters.</p></li>
<li><p><code>body_mass_g</code>: body mass of a penguin, in grams.</p></li>
</ol><p>To learn more about <code>penguins</code>, open its help page by running <code><a href="https://allisonhorst.github.io/palmerpenguins/reference/penguins.html">?penguins</a></code>.</p>
</section>
2023-01-13 07:22:57 +08:00
<section id="sec-ultimate-goal" data-type="sect2">
<h2>
2023-01-13 07:22:57 +08:00
Ultimate goal</h2>
<p>Our ultimate goal in this chapter is to recreate the following visualization displaying the relationship between flipper lengths and body masses of these penguins, taking into consideration the species of the penguin.</p>
<div class="cell">
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-7-1.png" alt="A scatterplot of body mass vs. flipper length of penguins, with a smooth curve displaying the relationship between these two variables overlaid. The plot displays a positive, fairly linear, and relatively strong relationship between these two variables. Species (Adelie, Chinstrap, and Gentoo) are represented with different colors and shapes. The relationship between body mass and flipper length is roughly the same for these three species, and Gentoo penguins are larger than penguins from the other two species." width="576"/></p>
</div>
</div>
</section>
2023-01-13 07:22:57 +08:00
<section id="creating-a-ggplot" data-type="sect2">
<h2>
2023-01-13 07:22:57 +08:00
Creating a ggplot</h2>
<p>Lets recreate this plot layer-by-layer.</p>
<p>With ggplot2, you begin a plot with the function <code><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot()</a></code>, defining a plot object that you then add layers to. The first argument of <code><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot()</a></code> is the dataset to use in the graph and So <code>ggplot(data = penguins)</code> creates an empty graph. This is not a very exciting plot, but you can think of it like an empty canvas youll paint the remaining layers of your plot onto.</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(data = penguins)</pre>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-8-1.png" alt="A blank, gray plot area." width="576"/></p>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>Next, we need to tell <code><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot()</a></code> the variables from this data frame that we want to map to visual properties (<strong>aesthetics</strong>) of the plot. The <code>mapping</code> argument of the <code><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot()</a></code> function defines how variables in your dataset are mapped to visual properties of your plot. The <code>mapping</code> argument is always paired with the <code><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes()</a></code> function, and the <code>x</code> and <code>y</code> arguments of <code><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes()</a></code> specify which variables to map to the x and y axes. For now, we will only map flipper length to the <code>x</code> aesthetic and body mass to the <code>y</code> aesthetic. ggplot2 looks for the mapped variables in the <code>data</code> argument, in this case, <code>penguins</code>.</p>
<p>The following plots show the result of adding these mappings, one at a time.</p>
<div>
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm)
)
ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
)</pre>
<div class="cell quarto-layout-panel">
<div class="quarto-layout-row quarto-layout-valign-top">
<div class="cell-output-display quarto-layout-cell" style="flex-basis: 50.0%;justify-content: center;">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-9-1.png" alt="There are two plots. The plot on the left is shows flipper length on the x-axis. The values range from 170 to 230 The plot on the right also shows body mass on the y-axis. The values range from 3000 to 6000." width="576"/></p>
</div>
<div class="cell-output-display quarto-layout-cell" style="flex-basis: 50.0%;justify-content: center;">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-9-2.png" alt="There are two plots. The plot on the left is shows flipper length on the x-axis. The values range from 170 to 230 The plot on the right also shows body mass on the y-axis. The values range from 3000 to 6000." width="576"/></p>
</div>
</div>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>Our empty canvas now has more structure its clear where flipper lengths will be displayed (on the x-axis) and where body masses will be displayed (on the y-axis). But the penguins themselves are not yet on the plot. This is because we have not yet articulated, in our code, how to represent the observations from our data frame on our plot.</p>
<p>To do so, we need to define a <strong>geom</strong>: the geometrical object that a plot uses to represent data. These geometric objects are made available in ggplot2 with functions that start with <code>geom_</code>. People often describe plots by the type of geom that the plot uses. For example, bar charts use bar geoms (<code><a href="https://ggplot2.tidyverse.org/reference/geom_bar.html">geom_bar()</a></code>), line charts use line geoms (<code><a href="https://ggplot2.tidyverse.org/reference/geom_path.html">geom_line()</a></code>), boxplots use boxplot geoms (<code><a href="https://ggplot2.tidyverse.org/reference/geom_boxplot.html">geom_boxplot()</a></code>), and so on. Scatterplots break the trend; they use the point geom: <code><a href="https://ggplot2.tidyverse.org/reference/geom_point.html">geom_point()</a></code>.</p>
<p>The function <code><a href="https://ggplot2.tidyverse.org/reference/geom_point.html">geom_point()</a></code> adds a layer of points to your plot, which creates a scatterplot. ggplot2 comes with many geom functions that each adds a different type of layer to a plot. Youll learn a whole bunch of geoms throughout the book, particularly in <a href="#chp-layers" data-type="xref">#chp-layers</a>.</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_point()
#&gt; Warning: Removed 2 rows containing missing values (`geom_point()`).</pre>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-10-1.png" alt="A scatterplot of body mass vs. flipper length of penguins. The plot displays a positive, linear, and relatively strong relationship between these two variables." width="576"/></p>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>Now we have something that looks like what we might think of as a “scatter plot”. It doesnt yet match our “ultimate goal” plot, but using this plot we can start answering the question that motivated our exploration: “What does the relationship between flipper length and body mass look like?” The relationship appears to be positive, fairly linear, and moderately strong. Penguins with longer flippers are generally larger in terms of their body mass.</p>
<p>Before we add more layers to this plot, lets pause for a moment and review the warning message we got:</p>
<blockquote class="blockquote">
<p>Removed 2 rows containing missing values (<code><a href="https://ggplot2.tidyverse.org/reference/geom_point.html">geom_point()</a></code>).</p>
</blockquote>
<p>Were seeing this message because there are two penguins in our dataset with missing body mass and flipper length values and ggplot2 has no way of representing them on the plot. You dont need to worry about understanding the following code yet (you will learn about it in <a href="#chp-data-transform" data-type="xref">#chp-data-transform</a>), but its one way of identifying the observations with <code>NA</code>s for either body mass or flipper length.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">penguins |&gt;
select(species, flipper_length_mm, body_mass_g) |&gt;
filter(is.na(body_mass_g) | is.na(flipper_length_mm))
#&gt; # A tibble: 2 × 3
#&gt; species flipper_length_mm body_mass_g
#&gt; &lt;fct&gt; &lt;int&gt; &lt;int&gt;
#&gt; 1 Adelie NA NA
#&gt; 2 Gentoo NA NA</pre>
</div>
<p>Like R, ggplot2 subscribes to the philosophy that missing values should never silently go missing. This type of warning is probably one of the most common types of warnings you will see when working with real data missing values are a very common issue and youll learn more about them throughout the book, particularly in <a href="#chp-missing-values" data-type="xref">#chp-missing-values</a>. For the remaining plots in this chapter we will suppress this warning so its not printed alongside every single plot we make.</p>
</section>
2023-01-13 07:22:57 +08:00
<section id="adding-aesthetics-and-layers" data-type="sect2">
<h2>
Adding aesthetics and layers</h2>
<p>Scatterplots are useful for displaying the relationship between two variables, but its always a good idea to be skeptical of any apparent relationship between two variables and ask if there may be other variables that explain or change the nature of this apparent relationship. Lets incorporate species into our plot and see if this reveals any additional insights into the apparent relationship between flipper length and body mass. We will do this by representing species with different colored points.</p>
<p>To achieve this, where should <code>species</code> go in the ggplot call from earlier? If you guessed “in the aesthetic mapping, inside of <code><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes()</a></code>”, youre already getting the hang of creating data visualizations with ggplot2! And if not, dont worry. Throughout the book you will make many more ggplots and have many more opportunities to check your intuition as you make them.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g, color = species)
) +
geom_point()</pre>
<div class="cell-output-display">
<p><img src="data-visualize_files/figure-html/unnamed-chunk-12-1.png" alt="A scatterplot of body mass vs. flipper length of penguins. The plot displays a positive, fairly linear, and relatively strong relationship between these two variables. Species (Adelie, Chinstrap, and Gentoo) are represented with different colors." width="576"/></p>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>When a variable is mapped to an aesthetic, ggplot2 will automatically assign a unique value of the aesthetic (here a unique color) to each unique level of the variable (each of the three species), a process known as <strong>scaling</strong>. ggplot2 will also add a legend that explains which values correspond to which levels.</p>
<p>Now lets add one more layer: a smooth curve displaying the relationship between body mass and flipper length. Before you proceed, refer back to the code above, and think about how we can add this to our existing plot.</p>
<p>Since this is a new geometric object representing our data, we will add a new geom: <code><a href="https://ggplot2.tidyverse.org/reference/geom_smooth.html">geom_smooth()</a></code>.</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g, color = species)
) +
geom_point() +
geom_smooth()</pre>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-13-1.png" alt="A scatterplot of body mass vs. flipper length of penguins. Overlaid on the scatterplot are three smooth curves displaying the relationship between these variables for each species (Adelie, Chinstrap, and Gentoo). Different penguin species are plotted in different colors for the points and the smooth curves." width="576"/></p>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>We have successfully added smooth curves, but this plot doesnt look like the plot from <a href="#sec-ultimate-goal" data-type="xref">#sec-ultimate-goal</a>, which only has one curve for the entire dataset as opposed to separate curves for each of the penguin species.</p>
<p>When aesthetic mappings are defined in <code><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot()</a></code>, at the <em>global</em> level, theyre inherited by each of the subsequent geom layers of the plot. However, each geom function in ggplot2 can also take a <code>mapping</code> argument, which allows for aesthetic mappings at the <em>local</em> level. Since we want points to be colored based on species but dont want the smooth curves to be separated out for them, we should specify <code>color = species</code> for <code><a href="https://ggplot2.tidyverse.org/reference/geom_point.html">geom_point()</a></code> only.</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_point(mapping = aes(color = species)) +
geom_smooth()</pre>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-14-1.png" alt="A scatterplot of body mass vs. flipper length of penguins. Overlaid on the scatterplot are is a single smooth curve displaying the relationship between these variables for each species (Adelie, Chinstrap, and Gentoo). Different penguin species are plotted in different colors for the points only." width="576"/></p>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>Voila! We have something that looks very much like our ultimate goal, though its not yet perfect. We still need to use different shapes for each species of penguins and improve labels.</p>
<p>Its generally not a good idea to represent information using only colors on a plot, as people perceive colors differently due to color blindness or other color vision differences. Therefore, in addition to color, we can also map <code>species</code> to the <code>shape</code> aesthetic.</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_point(mapping = aes(color = species, shape = species)) +
geom_smooth()</pre>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-15-1.png" alt="A scatterplot of body mass vs. flipper length of penguins. Overlaid on the scatterplot are is a single smooth curve displaying the relationship between these variables for each species (Adelie, Chinstrap, and Gentoo). Different penguin species are plotted in different colors and shapes for the points only." width="576"/></p>
</div>
</div>
<p>Note that the legend is automatically updated to reflect the different shapes of the points as well.</p>
<p>And finally, we can improve the labels of our plot using the <code><a href="https://ggplot2.tidyverse.org/reference/labs.html">labs()</a></code> function in a new layer. Some of the arguments to <code><a href="https://ggplot2.tidyverse.org/reference/labs.html">labs()</a></code> might be self explanatory: <code>title</code> adds a title and <code>subtitle</code> adds a subtitle to the plot. Other arguments match the aesthetic mappings, <code>x</code> is the x-axis label, <code>y</code> is the y-axis label, and <code>color</code> and <code>shape</code> define the label for the legend.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_point(aes(color = species, shape = species)) +
geom_smooth() +
labs(
title = "Body mass and flipper length",
subtitle = "Dimensions for Adelie, Chinstrap, and Gentoo Penguins",
x = "Flipper length (mm)",
y = "Body mass (g)",
color = "Species",
shape = "Species"
)</pre>
<div class="cell-output-display">
<p><img src="data-visualize_files/figure-html/unnamed-chunk-16-1.png" alt="A scatterplot of body mass vs. flipper length of penguins, with a smooth curve displaying the relationship between these two variables overlaid. The plot displays a positive, fairly linear, and relatively strong relationship between these two variables. Species (Adelie, Chinstrap, and Gentoo) are represented with different colors and shapes. The relationship between body mass and flipper length is roughly the same for these three species, and Gentoo penguins are larger than penguins from the other two species." width="576"/></p>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>We finally have a plot that perfectly matches our “ultimate goal”!</p>
</section>
<section id="data-visualize-exercises" data-type="sect2">
<h2>
Exercises</h2>
2023-01-13 07:22:57 +08:00
<ol type="1"><li><p>How many rows are in <code>penguins</code>? How many columns?</p></li>
<li><p>What does the <code>bill_depth_mm</code> variable in the <code>penguins</code> data frame describe? Read the help for <code><a href="https://allisonhorst.github.io/palmerpenguins/reference/penguins.html">?penguins</a></code> to find out.</p></li>
<li><p>Make a scatterplot of <code>bill_depth_mm</code> vs. <code>bill_length_mm</code>. Describe the relationship between these two variables.</p></li>
<li><p>What happens if you make a scatterplot of <code>species</code> vs <code>bill_depth_mm</code>? Why is the plot not useful?</p></li>
<li>
2023-01-13 07:22:57 +08:00
<p>Why does the following give an error and how would you fix it?</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(data = penguins) +
geom_point()</pre>
</div>
</li>
2023-01-13 07:22:57 +08:00
<li><p>What does the <code>na.rm</code> argument do in <code><a href="https://ggplot2.tidyverse.org/reference/geom_point.html">geom_point()</a></code>? What is the default value of the argument? Create a scatterplot where you successfully use this argument set to <code>TRUE</code>.</p></li>
<li><p>Add the following caption to the plot you made in the previous exercise: “Data come from the palmerpenguins package.” Hint: Take a look at the documentation for <code><a href="https://ggplot2.tidyverse.org/reference/labs.html">labs()</a></code>.</p></li>
<li>
2023-01-13 07:22:57 +08:00
<p>Recreate the following visualization. What aesthetic should <code>bill_depth_mm</code> be mapped to? And should it be mapped at the global level or at the geom level?</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<div class="cell-output-display">
<p><img src="data-visualize_files/figure-html/unnamed-chunk-18-1.png" alt="A scatterplot of body mass vs. flipper length of penguins, colored by bill depth. A smooth curve of the relationship between body mass and flipper length is overlaid. The relationship is positive, fairly linear, and moderately strong." width="576"/></p>
</div>
</div>
</li>
<li>
2023-01-13 07:22:57 +08:00
<p>Run this code in your head and predict what the output will look like. Then, run the code in R and check your predictions.</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g, color = island)
) +
geom_point() +
geom_smooth(se = FALSE)</pre>
</div>
</li>
<li>
2023-01-13 07:22:57 +08:00
<p>Will these two graphs look different? Why/why not?</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_point() +
geom_smooth()
ggplot() +
geom_point(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_smooth(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
)</pre>
</div>
</li>
</ol></section>
</section>
2023-01-13 07:22:57 +08:00
<section id="ggplot2-calls" data-type="sect1">
<h1>
2023-01-13 07:22:57 +08:00
ggplot2 calls</h1>
<p>As we move on from these introductory sections, well transition to a more concise expression of ggplot2 code. So far weve been very explicit, which is helpful when you are learning:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_point()</pre>
</div>
2023-01-13 07:22:57 +08:00
<p>Typically, the first one or two arguments to a function are so important that you should know them by heart. The first two arguments to <code><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot()</a></code> are <code>data</code> and <code>mapping</code>, in the remainder of the book, we wont supply those names. That saves typing, and, by reducing the amount of boilerplate, makes it easier to see whats different between plots. Thats a really important programming concern that well come back to in <a href="#chp-functions" data-type="xref">#chp-functions</a>.</p>
<p>Rewriting the previous plot more concisely yields:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">ggplot(penguins, aes(x = flipper_length_mm, y = body_mass_g)) +
geom_point()</pre>
</div>
2023-01-13 07:22:57 +08:00
<p>In the future, youll also learn about the pipe which will allow you to create that plot with:</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">penguins |&gt;
ggplot(aes(x = flipper_length_mm, y = body_mass_g)) +
geom_point()</pre>
</div>
2023-01-13 07:22:57 +08:00
<p>This is the most common syntax youll see in the wild.</p>
</section>
<section id="visualizing-distributions" data-type="sect1">
<h1>
Visualizing distributions</h1>
<p>How you visualize the distribution of a variable depends on the type of variable: categorical or numerical.</p>
<section id="a-categorical-variable" data-type="sect2">
<h2>
A categorical variable</h2>
<p>A variable is <strong>categorical</strong> if it can only take one of a small set of values. To examine the distribution of a categorical variable, you can use a bar chart. The height of the bars displays how many observations occurred with each <code>x</code> value.</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(penguins, aes(x = species)) +
geom_bar()</pre>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-24-1.png" alt="A bar chart of frequencies of species of penguins: Adelie (approximately 150), Chinstrap (approximately 90), Gentoo (approximately 125)." width="576"/></p>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>In bar plots of categorical variables with non-ordered levels, like the penguin <code>species</code> above, its often preferable to reorder the bars based on their frequencies. Doing so requires transforming the variable to a factor (how R handles categorical data) and then reordering the levels of that factor.</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(penguins, aes(x = fct_infreq(species))) +
geom_bar()</pre>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-25-1.png" alt="A bar chart of frequencies of species of penguins, where the bars are ordered in decreasing order of their heights (frequencies): Adelie (approximately 150), Gentoo (approximately 125), Chinstrap (approximately 90)." width="576"/></p>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>You will learn more about factors and functions for dealing with factors (like <code><a href="https://forcats.tidyverse.org/reference/fct_inorder.html">fct_infreq()</a></code> shown above) in <a href="#chp-factors" data-type="xref">#chp-factors</a>.</p>
</section>
<section id="a-numerical-variable" data-type="sect2">
<h2>
A numerical variable</h2>
<p>A variable is <strong>numerical</strong> if it can take any of an infinite set of ordered values. Numbers and date-times are two examples of continuous variables. To visualize the distribution of a continuous variable, you can use a histogram or a density plot.</p>
<div>
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(penguins, aes(x = body_mass_g)) +
geom_histogram(binwidth = 200)
ggplot(penguins, aes(x = body_mass_g)) +
geom_density()</pre>
<div class="cell quarto-layout-panel">
<div class="quarto-layout-row quarto-layout-valign-top">
2023-01-13 07:22:57 +08:00
<div class="cell-output-display quarto-layout-cell" style="flex-basis: 50.0%;justify-content: center;">
<p><img src="data-visualize_files/figure-html/unnamed-chunk-26-1.png" alt="A histogram (on the left) and density plot (on the right) of body masses of penguins. The distribution is unimodal and right skewed, ranging between approximately 2500 to 6500 grams." width="576"/></p>
</div>
2023-01-13 07:22:57 +08:00
<div class="cell-output-display quarto-layout-cell" style="flex-basis: 50.0%;justify-content: center;">
<p><img src="data-visualize_files/figure-html/unnamed-chunk-26-2.png" alt="A histogram (on the left) and density plot (on the right) of body masses of penguins. The distribution is unimodal and right skewed, ranging between approximately 2500 to 6500 grams." width="576"/></p>
</div>
</div>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>A histogram divides the x-axis into equally spaced bins and then uses the height of a bar to display the number of observations that fall in each bin. In the graph above, the tallest bar shows that 39 observations have a <code>body_mass_g</code> value between 3,500 and 3,700 grams, which are the left and right edges of the bar.</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">penguins |&gt;
count(cut_width(body_mass_g, 200))
#&gt; # A tibble: 19 × 2
#&gt; `cut_width(body_mass_g, 200)` n
#&gt; &lt;fct&gt; &lt;int&gt;
#&gt; 1 [2.7e+03,2.9e+03] 7
#&gt; 2 (2.9e+03,3.1e+03] 10
#&gt; 3 (3.1e+03,3.3e+03] 23
#&gt; 4 (3.3e+03,3.5e+03] 38
#&gt; 5 (3.5e+03,3.7e+03] 39
#&gt; 6 (3.7e+03,3.9e+03] 37
#&gt; # … with 13 more rows</pre>
</div>
2023-01-13 07:22:57 +08:00
<p>You can set the width of the intervals in a histogram with the binwidth argument, which is measured in the units of the <code>x</code> variable. You should always explore a variety of binwidths when working with histograms, as different binwidths can reveal different patterns. In the plots below a binwidth of 20 is too narrow, resulting in too many bars, making it difficult to determine the shape of the distribution. Similarly, a binwidth of 2,000 is too high, resulting in all data being binned into only three bars, and also making it difficult to determine the shape of the distribution.</p>
<div>
<pre data-type="programlisting" data-code-language="r">ggplot(penguins, aes(x = body_mass_g)) +
geom_histogram(binwidth = 20)
ggplot(penguins, aes(x = body_mass_g)) +
geom_histogram(binwidth = 200)
ggplot(penguins, aes(x = body_mass_g)) +
geom_histogram(binwidth = 2000)</pre>
<div class="cell quarto-layout-panel">
<div class="quarto-layout-row quarto-layout-valign-top">
<div class="cell-output-display quarto-layout-cell" style="flex-basis: 33.3%;justify-content: center;">
<p><img src="data-visualize_files/figure-html/unnamed-chunk-28-1.png" alt="Three histograms of body masses of penguins, one with binwidth of 20 (right), one with binwidth of 200 (center), and one with binwidth of 2000 (left). The histogram with binwidth of 20 shows lots of ups and downs in the heights of the bins, creating a jagged outline. The histogram with binwidth of 2000 shows only three bins." width="576"/></p>
</div>
2023-01-13 07:22:57 +08:00
<div class="cell-output-display quarto-layout-cell" style="flex-basis: 33.3%;justify-content: center;">
<p><img src="data-visualize_files/figure-html/unnamed-chunk-28-2.png" alt="Three histograms of body masses of penguins, one with binwidth of 20 (right), one with binwidth of 200 (center), and one with binwidth of 2000 (left). The histogram with binwidth of 20 shows lots of ups and downs in the heights of the bins, creating a jagged outline. The histogram with binwidth of 2000 shows only three bins." width="576"/></p>
</div>
2023-01-13 07:22:57 +08:00
<div class="cell-output-display quarto-layout-cell" style="flex-basis: 33.3%;justify-content: center;">
<p><img src="data-visualize_files/figure-html/unnamed-chunk-28-3.png" alt="Three histograms of body masses of penguins, one with binwidth of 20 (right), one with binwidth of 200 (center), and one with binwidth of 2000 (left). The histogram with binwidth of 20 shows lots of ups and downs in the heights of the bins, creating a jagged outline. The histogram with binwidth of 2000 shows only three bins." width="576"/></p>
</div>
</div>
</div>
</div>
2023-01-13 07:22:57 +08:00
</section>
<section id="data-visualize-exercises-1" data-type="sect2">
<h2>
Exercises</h2>
2023-01-13 07:22:57 +08:00
<ol type="1"><li><p>Make a bar plot of <code>species</code> of <code>penguins</code>, where you assign <code>species</code> to the <code>y</code> aesthetic. How is this plot different?</p></li>
<li>
2023-01-13 07:22:57 +08:00
<p>How are the following two plots different? Which aesthetic, <code>color</code> or <code>fill</code>, is more useful for changing the color of bars?</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(penguins, aes(x = species)) +
geom_bar(color = "red")
2023-01-13 07:22:57 +08:00
ggplot(penguins, aes(x = species)) +
geom_bar(fill = "red")</pre>
</div>
</li>
2023-01-13 07:22:57 +08:00
<li><p>What does the <code>bins</code> argument in <code><a href="https://ggplot2.tidyverse.org/reference/geom_histogram.html">geom_histogram()</a></code> do?</p></li>
<li><p>Make a histogram of the <code>carat</code> variable in the <code>diamonds</code> dataset. Experiment with different binwidths. What binwidth reveals the most interesting patterns?</p></li>
</ol></section>
</section>
2023-01-13 07:22:57 +08:00
<section id="visualizing-relationships" data-type="sect1">
<h1>
2023-01-13 07:22:57 +08:00
Visualizing relationships</h1>
<p>To visualize a relationship we need to have at least two variables mapped to aesthetics of a plot. In the following sections you will learn about commonly used plots for visualizing relationships between two or more variables and the geoms used for creating them.</p>
<section id="a-numerical-and-a-categorical-variable" data-type="sect2">
<h2>
A numerical and a categorical variable</h2>
<p>To visualize the relationship between a numerical and a categorical variable we can use side-by-side box plots. A <strong>boxplot</strong> is a type of visual shorthand for a distribution of values that is popular among statisticians. As shown in <a href="#fig-eda-boxplot" data-type="xref">#fig-eda-boxplot</a>, each boxplot consists of:</p>
<ul><li><p>A box that stretches from the 25th percentile of the distribution to the 75th percentile, a distance known as the interquartile range (IQR). In the middle of the box is a line that displays the median, i.e. 50th percentile, of the distribution. These three lines give you a sense of the spread of the distribution and whether or not the distribution is symmetric about the median or skewed to one side.</p></li>
<li><p>Visual points that display observations that fall more than 1.5 times the IQR from either edge of the box. These outlying points are unusual so are plotted individually.</p></li>
<li><p>A line (or whisker) that extends from each end of the box and goes to the farthest non-outlier point in the distribution.</p></li>
</ul><div class="cell">
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<figure id="fig-eda-boxplot"><p><img src="images/EDA-boxplot.png" alt="A diagram depicting how a boxplot is created following the steps outlined above." width="1066"/></p>
<figcaption>Diagram depicting how a boxplot is created.</figcaption>
</figure>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>Lets take a look at the distribution of body mass by species using <code><a href="https://ggplot2.tidyverse.org/reference/geom_boxplot.html">geom_boxplot()</a></code>:</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(penguins, aes(x = species, y = body_mass_g)) +
geom_boxplot()</pre>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-31-1.png" alt="Side-by-side box plots of distributions of body masses of Adelie, Chinstrap, and Gentoo penguins. The distribution of Adelie and Chinstrap penguins' body masses appear to be symmetric with medians around 3750 grams. The median body mass of Gentoo penguins is much higher, around 5000 grams, and the distribution of the body masses of these penguins appears to be somewhat right skewed." width="576"/></p>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>Alternatively, we can make frequency polygons with <code><a href="https://ggplot2.tidyverse.org/reference/geom_histogram.html">geom_freqpoly()</a></code>. <code><a href="https://ggplot2.tidyverse.org/reference/geom_histogram.html">geom_freqpoly()</a></code> performs the same calculation as <code><a href="https://ggplot2.tidyverse.org/reference/geom_histogram.html">geom_histogram()</a></code>, but instead of displaying the counts with bars, it uses lines instead. Its much easier to understand overlapping lines than bars of <code><a href="https://ggplot2.tidyverse.org/reference/geom_histogram.html">geom_histogram()</a></code>. There are a few challenges with this type of plot, which we will come back to in <a href="#sec-cat-num" data-type="xref">#sec-cat-num</a> on exploring the covariation between a categorical and a numerical variable.</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(penguins, aes(x = body_mass_g, color = species)) +
geom_freqpoly(binwidth = 200, linewidth = 0.75)</pre>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-32-1.png" alt="A frequency polygon of body masses of penguins by species of penguins. Each species (Adelie, Chinstrap, and Gentoo) is represented with different colored outlines for the polygons." width="576"/></p>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>Weve also customized the thickness of the lines using the <code>linewidth</code> argument in order to make them stand out a bit more against the background.</p>
<p>We can also use overlaid density plots, with <code>species</code> mapped to both <code>color</code> and <code>fill</code> aesthetics and using the <code>alpha</code> aesthetic to add transparency to the filled density curves. This aesthetic takes values between 0 (completely transparent) and 1 (completely opaque). In the following plot its <em>set</em> to 0.5.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">ggplot(penguins, aes(x = body_mass_g, color = species, fill = species)) +
geom_density(alpha = 0.5)</pre>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-33-1.png" alt="A frequency polygon of body masses of penguins (on the left) and density plot (on the right). Each species of penguins (Adelie, Chinstrap, and Gentoo) are represented in different colored outlines for the frequency polygons and the density curves. The density curves are also filled with the same colors, with some transparency added." width="576"/></p>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>Note the terminology we have used here:</p>
<ul><li>We <em>map</em> variables to aesthetics if we want the visual attribute represented by that aesthetic to vary based on the values of that variable.</li>
<li>Otherwise, we <em>set</em> the value of an aesthetic.</li>
</ul></section>
<section id="data-visualize-two-categorical-variables" data-type="sect2">
<h2>
2023-01-13 07:22:57 +08:00
Two categorical variables</h2>
<p>We can use segmented bar plots to visualize the distribution between two categorical variables. In creating this bar chart, we map the variable we want to divide the data into first to the <code>x</code> aesthetic and the variable we then further want to divide each group into to the <code>fill</code> aesthetic.</p>
<p>Below are two segmented bar plots, both displaying the relationship between <code>island</code> and <code>species</code>, or specifically, visualizing the distribution of <code>species</code> within each island. The plot on the left shows the frequencies of each species of penguins on each island and the plot on the right shows the relative frequencies (proportions) of each species within each island (despite the incorrectly labeled y-axis that says “count”). The relative frequency plot, created by setting <code>position = "fill"</code> in the geom is more useful for comparing species distributions across islands since its not affected by the unequal numbers of penguins across the islands. Based on the plot on the left, we can see that Gentoo penguins all live on Biscoe island and make up roughly 75% of the penguins on that island, Chinstrap all live on Dream island and make up roughly 50% of the penguins on that island, and Adelie live on all three islands and make up all of the penguins on Torgersen.</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(penguins, aes(x = island, fill = species)) +
geom_bar()
ggplot(penguins, aes(x = island, fill = species)) +
geom_bar(position = "fill")</pre>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-34-1.png" alt="Bar plots of penguin species by island (Biscoe, Dream, and Torgersen). On the right, frequencies of species are shown. On the left, relative frequencies of species are shown." width="576"/></p>
</div>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-34-2.png" alt="Bar plots of penguin species by island (Biscoe, Dream, and Torgersen). On the right, frequencies of species are shown. On the left, relative frequencies of species are shown." width="576"/></p>
</div>
</div>
2023-01-13 07:22:57 +08:00
</section>
<section id="data-visualize-two-numerical-variables" data-type="sect2">
2023-01-13 07:22:57 +08:00
<h2>
Two numerical variables</h2>
<p>So far youve learned about scatterplots (created with <code><a href="https://ggplot2.tidyverse.org/reference/geom_point.html">geom_point()</a></code>) and smooth curves (created with <code><a href="https://ggplot2.tidyverse.org/reference/geom_smooth.html">geom_smooth()</a></code>) for visualizing the relationship between two numerical variables. A scatterplot is probably the most commonly used plot for visualizing the relationship between two variables.</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(penguins, aes(x = flipper_length_mm, y = body_mass_g)) +
geom_point()</pre>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-35-1.png" alt="A scatterplot of body mass vs. flipper length of penguins. The plot displays a positive, linear, relatively strong relationship between these two variables." width="576"/></p>
</div>
</div>
2023-01-13 07:22:57 +08:00
</section>
<section id="three-or-more-variables" data-type="sect2">
<h2>
Three or more variables</h2>
<p>One way to add additional variables to a plot is by mapping them to an aesthetic. For example, in the following scatterplot the colors of points represent species and the shapes of points represent islands.</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(penguins, aes(x = flipper_length_mm, y = body_mass_g)) +
geom_point(aes(color = species, shape = island))</pre>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-36-1.png" alt="A scatterplot of body mass vs. flipper length of penguins. The plot displays a positive, linear, relatively strong relationship between these two variables. The points are colored based on the species of the penguins and the shapes of the points represent islands (round points are Biscoe island, triangles are Dream island, and squared are Torgersen island). The plot is very busy and it's difficult to distinguish the shapes of the points." width="576"/></p>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>However adding too many aesthetic mappings to a plot makes it cluttered and difficult to make sense of. Another way, which is particularly useful for categorical variables, is to split your plot into <strong>facets</strong>, subplots that each display one subset of the data.</p>
<p>To facet your plot by a single variable, use <code><a href="https://ggplot2.tidyverse.org/reference/facet_wrap.html">facet_wrap()</a></code>. The first argument of <code><a href="https://ggplot2.tidyverse.org/reference/facet_wrap.html">facet_wrap()</a></code> is a formula<span data-type="footnote">Here “formula” is the name of the type of thing created by <code>~</code>, not a synonym for “equation”.</span>, which you create with <code>~</code> followed by a variable name. The variable that you pass to <code><a href="https://ggplot2.tidyverse.org/reference/facet_wrap.html">facet_wrap()</a></code> should be categorical.</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(penguins, aes(x = flipper_length_mm, y = body_mass_g)) +
geom_point(aes(color = species, shape = species)) +
facet_wrap(~island)</pre>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-37-1.png" alt="A scatterplot of body mass vs. flipper length of penguins. The shapes and colors of points represent species. Penguins from each island are on a separate facet. Within each facet, the relationship between body mass and flipper length is positive, linear, relatively strong." width="768"/></p>
</div>
</div>
2023-01-13 07:22:57 +08:00
<p>You will learn about many other geoms for visualizing distributions of variables and relationships between them in <a href="#chp-layers" data-type="xref">#chp-layers</a>.</p>
</section>
<section id="data-visualize-exercises-2" data-type="sect2">
<h2>
Exercises</h2>
2023-01-13 07:22:57 +08:00
<ol type="1"><li><p>Which variables in <code>mpg</code> are categorical? Which variables are continuous? (Hint: type <code><a href="https://ggplot2.tidyverse.org/reference/mpg.html">?mpg</a></code> to read the documentation for the dataset). How can you see this information when you run <code>mpg</code>?</p></li>
<li><p>Make a scatterplot of <code>hwy</code> vs. <code>displ</code> using the <code>mpg</code> data frame. Next, map a third, numerical variable to <code>color</code>, then <code>size</code>, then both <code>color</code> and <code>size</code>, then <code>shape</code>. How do these aesthetics behave differently for categorical vs. numerical variables?</p></li>
<li><p>In the scatterplot of <code>hwy</code> vs. <code>displ</code>, what happens if you map a third variable to <code>linewidth</code>?</p></li>
<li><p>What happens if you map the same variable to multiple aesthetics?</p></li>
<li><p>Make a scatterplot of <code>bill_depth_mm</code> vs. <code>bill_length_mm</code> and color the points by <code>species</code>. What does adding coloring by species reveal about the relationship between these two variables?</p></li>
<li>
<p>Why does the following yield two separate legends? How would you fix it to combine the two legends?</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(
data = penguins,
mapping = aes(
x = bill_length_mm, y = bill_depth_mm,
color = species, shape = species
)
) +
geom_point() +
labs(color = "Species")</pre>
<div class="cell-output-display">
2023-01-13 07:22:57 +08:00
<p><img src="data-visualize_files/figure-html/unnamed-chunk-38-1.png" alt="Scatterplot of bill depth vs. bill length where different color and shape pairings represent each species. The plot has two legends, one labelled &quot;species&quot; which shows the shape scale and the other that shows the color scale." width="576"/></p>
</div>
</div>
</li>
</ol></section>
</section>
2023-01-13 07:22:57 +08:00
<section id="sec-ggsave" data-type="sect1">
<h1>
2023-01-13 07:22:57 +08:00
Saving your plots</h1>
<p>Once youve made a plot, you might want to get it out of R by saving it as an image that you can use elsewhere. Thats the job of <code><a href="https://ggplot2.tidyverse.org/reference/ggsave.html">ggsave()</a></code>, which will save the most recent plot to disk:</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(penguins, aes(x = flipper_length_mm, y = body_mass_g)) +
geom_point()
ggsave(filename = "my-plot.png")</pre>
</div>
2023-01-13 07:22:57 +08:00
<p>This will save your plot to your working directory, a concept youll learn more about in <a href="#chp-workflow-scripts" data-type="xref">#chp-workflow-scripts</a>.</p>
<p>If you dont specify the <code>width</code> and <code>height</code> they will be taken from the dimensions of the current plotting device. For reproducible code, youll want to specify them. You can learn more about <code><a href="https://ggplot2.tidyverse.org/reference/ggsave.html">ggsave()</a></code> in the documentation.</p>
<p>Generally, however, we recommend that you assemble your final reports using Quarto, a reproducible authoring system that allows you to interleave your code and your prose and automatically include your plots in your write-ups. You will learn more about Quarto in <a href="#chp-quarto" data-type="xref">#chp-quarto</a>.</p>
<section id="data-visualize-exercises-3" data-type="sect2">
<h2>
Exercises</h2>
2023-01-13 07:22:57 +08:00
<ol type="1"><li>
<p>Run the following lines of code. Which of the two plots is saved as <code>mpg-plot.png</code>? Why?</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(mpg, aes(x = class)) +
geom_bar()
ggplot(mpg, aes(x = cty, y = hwy)) +
geom_point()
ggsave("mpg-plot.png")</pre>
</div>
</li>
2023-01-13 07:22:57 +08:00
<li><p>What do you need to change in the code above to save the plot as a PDF instead of a PNG?</p></li>
</ol></section>
</section>
2023-01-13 07:22:57 +08:00
<section id="common-problems" data-type="sect1">
<h1>
2023-01-13 07:22:57 +08:00
Common problems</h1>
<p>As you start to run R code, youre likely to run into problems. Dont worry — it happens to everyone. We have all been writing R code for years, but every day we still write code that doesnt work!</p>
<p>Start by carefully comparing the code that youre running to the code in the book. R is extremely picky, and a misplaced character can make all the difference. Make sure that every <code>(</code> is matched with a <code>)</code> and every <code>"</code> is paired with another <code>"</code>. Sometimes youll run the code and nothing happens. Check the left-hand of your console: if its a <code>+</code>, it means that R doesnt think youve typed a complete expression and its waiting for you to finish it. In this case, its usually easy to start from scratch again by pressing ESCAPE to abort processing the current command.</p>
<p>One common problem when creating ggplot2 graphics is to put the <code>+</code> in the wrong place: it has to come at the end of the line, not the start. In other words, make sure you havent accidentally written code like this:</p>
<div class="cell">
2023-01-13 07:22:57 +08:00
<pre data-type="programlisting" data-code-language="r">ggplot(data = mpg)
+ geom_point(mapping = aes(x = displ, y = hwy))</pre>
</div>
2023-01-13 07:22:57 +08:00
<p>If youre still stuck, try the help. You can get help about any R function by running <code>?function_name</code> in the console, or selecting the function name and pressing F1 in RStudio. Dont worry if the help doesnt seem that helpful - instead skip down to the examples and look for code that matches what youre trying to do.</p>
<p>If that doesnt help, carefully read the error message. Sometimes the answer will be buried there! But when youre new to R, even if the answer is in the error message, you might not yet know how to understand it. Another great tool is Google: try googling the error message, as its likely someone else has had the same problem, and has gotten help online.</p>
</section>
<section id="data-visualize-summary" data-type="sect1">
<h1>
Summary</h1>
2023-01-13 07:22:57 +08:00
<p>In this chapter, youve learned the basics of data visualization with ggplot2. We started with the basic idea that underpins ggplot2: a visualization is a mapping from variables in your data to aesthetic properties like position, color, size and shape. You then learned about increasing the complexity and improving the presentation of your plots layer-by-layer. You also learned about commonly used plots for visualizing the distribution of a single variable as well as for visualizing relationships between two or more variables, by levering additional aesthetic mappings and/or splitting your plot into small multiples using faceting.</p>
<p>Well use visualizations again and again through out this book, introducing new techniques as we need them as well as do a deeper dive into creating visualizations with ggplot2 in <a href="#chp-layers" data-type="xref">#chp-layers</a> through <a href="#chp-EDA" data-type="xref">#chp-EDA</a>.</p>
<p>With the basics of visualization under your belt, in the next chapter were going to switch gears a little and give you some practical workflow advice. We intersperse workflow advice with data science tools throughout this part of the book because itll help you stay organized as you write increasing amounts of R code.</p>
</section>
</section>