Why doesn’t this code work?
mtcars |> ggplot(., aes(x = mpg, y = hp)) + geom_point()
The problem with the code above lies in the use of the pipe operator (|>), right before ggplot. ggplot2 is not natively supported with the R-specific pipe (|>), as used here. However, ggplot2 works seamlessly with the Magrittr pipe (%>%) from the dplyr package. Here is the correct usage:
library(ggplot2)
library(dplyr)
mtcars %>%
ggplot(aes(x = mpg, y = hp)) +
geom_point()
Alternatively, the data must be explicitly passed to ggplot, as shown here:
library(ggplot2)
mtcars |>
ggplot(data = ., aes(x = mpg, y = hp)) +
geom_point()
Here, the dot (.) represents the data being piped from mtcars
into ggplot
, and you need to specify it as the data
argument in the ggplot function.