The “facet_grid” Function in R
Package: ggplot2
Purpose: To create a grid of small multiples in ggplot.
General Class: Geometric object for facetting into a grid.
Required Argument(s): None
Notable Optional Arguments:
facets: Formula specifying rows and columns.
scales: Should scales be fixed (“fixed”), free (“free”), or free in one dimension (“free_x” or “free_y”).
space: If “fixed”, the total space (width or height); if “free”, the space between facets.
shrink: If TRUE, will shrink scales to fit output of statistics, not raw data.
labeller: A function that takes one data frame of labels and returns a data frame of labels.
as.table: If TRUE, the default, the facets are laid out like a table with the highest values at the bottom-right.
Example:
# Example usage
library(ggplot2)
# Create a data frame
my_data <- data.frame(
group = rep(c("A", "B", "C"), each = 50),
values = rnorm(150)
)
# Create a ggplot object with a facetted grid using facet_grid
my_plot <- ggplot(data = my_data, aes(x = values, y = after_stat(density))) +
geom_histogram(binwidth = 0.5, fill = "lightblue", color = "blue", alpha = 0.7) +
facet_grid(group ~ ., scales = "free_y") +
labs(title = "Facetted Histogram", x = "Values", y = "Density")
# Print the plot
print(my_plot)In this example, the facet_grid function from the ggplot2 package is used to create a facetted grid of histograms. The function allows the specification of facets using a formula, and optional arguments control the arrangement and scales of the facets.