ggplot basics

Summary for Lecture 3,4,5 DANL 310

ggplot
visualization
Author

Jordan A

Published

February 12, 2025

Introduction

ggplot2 is a powerful and flexible R package for creating data visualizations. It follows the Grammar of Graphics approach, allowing users to layer components to build complex plots systematically.

Key Concepts

1. Creating a Basic Plot

To create a ggplot, you start with the ggplot() function, specifying a dataset and mapping aesthetics using aes().

library(ggplot2)
ggplot(data = mpg, aes(x = displ, y = hwy)) +
  geom_point()

2. Adding Layers

Layers such as geom_point(), geom_line(), and geom_bar() define how data is represented.

ggplot(mpg, aes(x = class)) +
  geom_bar()

3. Customizing the Appearance

Themes, scales, and labels allow customization.

ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point(color = "blue") +
  labs(title = "Displacement vs Highway MPG", x = "Engine Displacement", y = "Highway MPG") +
  theme_minimal()

4. Faceting

Faceting creates small multiples based on categorical variables.

ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point() +
  facet_wrap(~ class)

Conclusion

ggplot2 provides an intuitive way to build visualizations layer by layer. Mastering these basics sets a strong foundation for more advanced customizations and analyses.