[ggplot2](https://ggplot2.tidyverse.org/) is a [[data visualization]] package in [[R]] bundled with [[tidyverse]].
## installation
The easiest way to get ggplot2 is to install the whole `tidyverse`. Alternatively, install just `ggplot2`.
```R
# Install tidyverse
install.packages("tidyverse")
# Alternatively, install ggplot2
install.packages("ggplot2")
```
## use
`ggplot2` leverages the [[grammar of graphics]] to build data visualizations. Start with a call to `ggplot(<data>)` passing in [[tidy]] data as the argument, then add aesthetics with `aes()` and then add layers like `geom_point()` or `geom_histogram()`. Optionally, add scales, facets, coordinate systems and themes.
Here's an example using the built-in `mpg` dataset.
```R
library(ggplot2)
ggplot(mpg) +
aes(x = displ, y = hwy)) +
geom_point(aes(color = class)) +
geom_smooth(se = FALSE) +
labs(
x = "Engine displacement (L)",
y = "Highway fuel economy (mpg)",
color = "Car type",
title = "Fuel efficiency generally decreases with engine size",
subtitle = "Two seaters (sports cars) are an exception because of their light weight",
caption = "Data from fueleconomy.gov"
)
```

Easily update a plot by adding layers to a saved plot object.
```R
plot <- ggplot(mpg) +
aes(x = displ, y = hwy) +
geom_point(aes(color = class))
plot <- plot + geom_smooth(se = FALSE)
```
## extension packages
Use extension packages for additional functionality.
`gridExtra` supports subplots.
```R
library(gridExtra)
# Plot each chart
plot1 <- ggplot(...)
plot2 <- ggplot(...)
plot3 <- ggplot(...)
# Arrange with grid.arrange
grid.arrange(plot1, plot2, plot3, nrow=3)
```
## additional features
For more, including annotations, scales, legends, and more, read the [Data Visualization](https://r4ds.hadley.nz/data-visualize) and [Communication](https://r4ds.hadley.nz/communication) chapters [[R for Data Science]].
## getting help
The [RStudio community](https://forum.posit.co/) is a friendly place to ask any questions about ggplot2.
[Stack Overflow](https://stackoverflow.com/questions/tagged/ggplot2?sort=frequent&pageSize=50) is a great source of answers to common ggplot2 questions. It is also a great place to get help, once you have created a reproducible example that illustrates your problem.
> [!tip]- Additional Resources
> - [Data Visualization in R With ggplot2](https://learning.oreilly.com/videos/data-visualization-in/9781491963661/) online course by Kara Woo
> - [The R Graphics Cookbook](https://r-graphics.org/) by Winston Chang
> - [ggplot2: Elegant Graphics for Data Analysis](https://ggplot2-book.org/) (for advanced users)