ggplot2 Cheat Sheet

Here’s a cheat sheet for ggplot2, a popular data visualization package in R:

Basic ggplot Structure

library(ggplot2)

ggplot(data = dataset, aes(x = x_variable, y = y_variable)) +
  geom_point()  # or other geometry functions like geom_line(), geom_bar(), etc.

Customizing Aesthetics

Color by a Variable:

ggplot(data = dataset, aes(x = x_variable, y = y_variable, color = categorical_variable)) +
  geom_point()

Size by a Variable:

ggplot(data = dataset, aes(x = x_variable, y = y_variable, size = numeric_variable)) +
  geom_point()

Faceting

Facet by a Variable:

ggplot(data = dataset, aes(x = x_variable, y = y_variable)) +
  geom_point() +
  facet_wrap(~ categorical_variable)

Themes and Labels

Change Theme:

ggplot(data = dataset, aes(x = x_variable, y = y_variable)) +
  geom_point() +
  theme_minimal()

Customize Axis Labels and Title:

ggplot(data = dataset, aes(x = x_variable, y = y_variable)) +
  geom_point() +
  labs(x = "X Axis Label", y = "Y Axis Label", title = "Plot Title")

Statistical Transformations

Add Smooth Line:

ggplot(data = dataset, aes(x = x_variable, y = y_variable)) +
  geom_point() +
  geom_smooth(method = "lm")

Histogram:

ggplot(data = dataset, aes(x = numeric_variable)) +
  geom_histogram(binwidth = 5, fill = "blue", color = "black", alpha = 0.7)

Multiple Layers

ggplot(data = dataset, aes(x = x_variable, y = y_variable)) +
  geom_point(color = "blue") +
  geom_smooth(method = "lm", color = "red", linetype = "dashed", se = FALSE) +
  theme_minimal()

Save Plot

Save as Image:

ggsave("plot.png", plot = last_plot(), width = 6, height = 4)

This cheat sheet provides a starting point for using ggplot2. For more advanced customization and details, refer to the official ggplot2 documentation.