Search code examples
rggplot2visualizationfacet-grid

How to add more rows to facet_grid() when I am already defining grids for my column?


I have the following data set:

set.seed(7736)
categories <- rep(LETTERS[1:11], each = 30)
values <- sample(50:200, 330, replace = T)
df <- data.frame(category = categories, values = values)

And I am creating the following graph:

graph_builder <- function(data_set, y_axis_parameter, category, attribute_name) {
  data_set <- data_set |>
    mutate(x = row_number(), .by = {{ category }})
  graph <- ggplot(data_set, aes(
    x = x,
    y = {{ y_axis_parameter }}, colour = {{ category }},
    group = 1
  )) +
    geom_line() +
    geom_point() +
    facet_grid(cols = vars({{ category }}), scales = "free_x") +
    ylab(paste0(attribute_name, " Measured Values")) +
    xlab("Data Points") +
    labs(title = paste0(attribute_name)) +
    theme(plot.title = element_text(hjust = 0.5)) +
    theme(legend.position = "none")

  graph
}

As you see my grids are the categories.

enter image description here

What I want to do is instead of having all the data shown in one row, I want to have 2 or 3 rows, so the graph is more readable. When I pass nrows= 2 to facet_grid(), I get error that the number of rows must be "NULL".

Question: Is there a parameter that I can pass to facet_grid() that automatically split my data into more rows (lets say 2 or 3). As you see, in the above graph, I have 11 groups, so if I choose to have two rows then one of the rows must display more number of categories (6 categories for the first row and 5 for the second). Or if I want to display data in 3 rows then 11 is not divisible by 3 and I don't know even if facet_grid() would be able to do what I am looking for. Any help would be really appreciated.


Solution

  • You can use facet_wrap() instead of facet_grid(). It will automatically pick a reasonable ratio of cols to rows.

    library(tidyverse)
    
    graph_builder <- function(data_set, y_axis_parameter, category, attribute_name) {
      data_set <- data_set |>
        mutate(x = row_number(), .by = {{ category }})
      graph <- ggplot(data_set, aes(
        x = x,
        y = {{ y_axis_parameter }}, colour = {{ category }},
        group = 1
      )) +
        geom_line() +
        geom_point() +
        facet_wrap(vars({{category}}), scales = "free_x") +
        ylab(paste0(attribute_name, " Measured Values")) +
        xlab("Data Points") +
        labs(title = paste0(attribute_name)) +
        theme(plot.title = element_text(hjust = 0.5)) +
        theme(legend.position = "none")
      
      graph
    }
    
    df |> 
      graph_builder(values, category, "blargh")
    

    
    df |> 
      filter(category %in% LETTERS[1:5]) |> 
      graph_builder(values, category, "blargh")