The “facet_wrap” Function in R

  • Package: ggplot2

  • Purpose: To create a multi-panel display of plots based on a categorical variable, wrapping the panels into a grid.

  • General Class: Plot Facet

  • Required Argument(s):

    • facets: A formula specifying the variables to be faceted, separated by a tilde (~).

  • Notable Optional Arguments:

    • ncol, nrow: Number of columns or rows in the grid of facets.

    • scales: Should scales be fixed (“fixed”) or free (“free”) across facets?

    • labeller: A function or character vector for custom labeling of facets.

  • Example:

  • # Example usage
    library(ggplot2)

    # Create a data frame
    my_data <- data.frame(
    Category = rep(c("A", "B", "C", "D"), each = 4),
    Value = rnorm(16)
    )

    # Create a ggplot object with faceted panels
    my_plot <- ggplot(data = my_data, aes(x = Category, y = Value)) +
    geom_boxplot() +
    facet_wrap(~Category, ncol = 2) +
    labs(title = "Faceted Boxplots by Category", x = "Category", y = "Value")

    # Print the faceted plot
    print(my_plot)

  • In this example, the facet_wrap function from the ggplot2 package is used to create a multi-panel display of boxplots, with each panel representing a different category. The ncol argument controls the number of columns in the grid of facets. Additional optional arguments customize the facet layout.

Previous
Previous

The “scale_x_continuous” Function in R

Next
Next

The “geom_line” Function in R