Example 03: Some basic plots

We make plots with the ggplot() function and some geom_ function. The former sets up the plot by specifying the data we are using and the relationships we want to see. The latter draws a specific kind of plot based on that information.

As always we load the packages we need. Here in addition to the tidyverse we load the gapminder data as a package.

Code
library(tidyverse)
library(gapminder)
Code
gapminder
# A tibble: 1,704 × 6
   country     continent  year lifeExp      pop gdpPercap
   <fct>       <fct>     <int>   <dbl>    <int>     <dbl>
 1 Afghanistan Asia       1952    28.8  8425333      779.
 2 Afghanistan Asia       1957    30.3  9240934      821.
 3 Afghanistan Asia       1962    32.0 10267083      853.
 4 Afghanistan Asia       1967    34.0 11537966      836.
 5 Afghanistan Asia       1972    36.1 13079460      740.
 6 Afghanistan Asia       1977    38.4 14880372      786.
 7 Afghanistan Asia       1982    39.9 12881816      978.
 8 Afghanistan Asia       1987    40.8 13867957      852.
 9 Afghanistan Asia       1992    41.7 16317921      649.
10 Afghanistan Asia       1997    41.8 22227415      635.
# ℹ 1,694 more rows

We saw that we can put plots in to objects, like this:

Code
p <- ggplot(data = gapminder, 
       mapping = aes(x = gdpPercap, y = lifeExp)) +
  geom_point()

p

We can set them up in a pipeline, too:

Code
gapminder |> 
  ggplot(mapping = aes(x = gdpPercap, y = lifeExp)) + 
  geom_point()

Experiment with some aesthetics, geoms, and transformations:

Code
gapminder |> 
  ggplot(mapping = aes(x = log(gdpPercap), y = lifeExp)) + 
  geom_point() + 
  geom_smooth()
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

Code
gapminder |> 
  ggplot(mapping = aes(x = lifeExp)) + 
  geom_histogram()
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Selecting a bin width:

Code
gapminder |> 
  ggplot(mapping = aes(x = lifeExp)) + 
  geom_histogram(binwidth = 5)