ggplot2::ggplot()
   get_help()
docs
The ggplot()
function is part of the {ggplot2}
package, which is part of the {tidyverse}
.
We use the ggplot()
function to establish a baseline {ggplot2}
plot. Note that the function does not end in the number 2! Most commonly, we provide this function with the data
argument of a tibble (data frame) whose data should be plotted. Optionally, we can also provide aesthetic mappings with aes()
, which will automatically be applied to all geoms.
To use this function, you need to either first load the {ggplot2}
library, or always use the function with ggplot2::ggplot()
notation.
# Load the library
library(ggplot2)
# Or, load the full tidyverse:
library(tidyverse)
# Or, use :: notation
::ggplot() ggplot2
# You can use the 'data' and 'mapping' argument keywords if you chose, but they are not required
ggplot(data = tibble or data frame to plot,
mapping = aes(optional aethestic mappings))
# `ggplot()` assumes the first argument is the data, and the second argument (if present) is aethetics
ggplot(tibble or data frame to plot,
aes(optional aethestic mappings))
# The aes() argument is not required at all:
ggplot(tibble or data frame to plot)
The examples below use the msleep
dataset. Learn more about this dataset with get_help("msleep")
.
# Show the msleep dataset with head()
head(msleep)
## # A tibble: 6 × 11
## name genus vore order conservation sleep_total sleep_rem sleep_cycle awake brainwt bodywt
## <chr> <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 Owl … Aotus omni Prim… <NA> 17 1.8 NA 7 0.0155 0.48
## 2 Moun… Aplo… herbi Rode… nt 14.4 2.4 NA 9.6 NA 1.35
## 3 Grea… Blar… omni Sori… lc 14.9 2.3 0.133 9.1 0.00029 0.019
## 4 Cow Bos herbi Arti… domesticated 4 0.7 0.667 20 0.423 600
## 5 Thre… Brad… herbi Pilo… <NA> 14.4 2.2 0.767 9.6 NA 3.85
## 6 Nort… Call… carni Carn… vu 8.7 1.4 0.383 15.3 NA 20.5
# Calling ggplot by itself establishes a blank canvas using the default theme:
ggplot()
# Calling ggplot with data and mappings but without a geom sets up axes:
ggplot(msleep,
aes(x = vore, y = awake))
# Make a boxplot with `vore` on the x-axis and `awake` on the y-axis
# This example provides aes() inside ggplot()
# Note, to remove NAs, you must manipulate the data first
ggplot(msleep,
aes(x = vore, y = awake)) +
geom_boxplot()
# Make a boxplot with `vore` on the x-axis and `awake` on the y-axis, with aes() on its own
# This examples provides aes() separately, outside of ggplot()
# Note, to remove NAs, you must manipulate the data first
ggplot(msleep) +
aes(x = vore, y = awake) +
geom_boxplot()