Search code examples
rggplot2visualizationfacet-grid

How to free up facet_grid() width in ggplot2?


My question is probably simple, but I couldn't find the solution. So any help would be very much appreciated. What I want to do is free up the width of the grids in facet_grid. I know that "free_x" should work, but it doesn't. facet_wrap() neither do the job.

The code is:

set.seed(1233)
means <- c(rep(20, 20), rep(60, 60), rep(120, 120))
sds <- c(rep(1, 20), rep(2, 60), rep(4, 120))
values <- rnorm(length(means), mean = means, sd = sds)
stage <- sample(c(rep("a", 20), rep("b", 60), rep("c", 120)))
df <- data.frame(cbind(values, stage))
rm(values)


graph_builder <- function(data_set, y_axis_parameter, category, attribute_name) {
  graph <- ggplot(data_set, aes(x=seq(length({{y_axis_parameter}})),
                                y={{y_axis_parameter}}, colour= {{category}})) +
    geom_line() +
    geom_point() +
    facet_grid(cols= vars({{category}})) +
    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
}


graph_builder(df, values, stage, "Test")

The issue is that if my stage categories are in order, such as 1-20: 'a,' 20-80: 'b,' and 80-200: 'c,' then the grids are shown respectively. However, I want each grid to start displaying data points from 1 to the length() of the number of data points for each category. It seems that facet_grid works based on the index, and I don't want that. Adding 'scales='free_x', space='free_x' in facet grid isn't my solution. What can I do?


Solution

  • Perhaps this is what you are looking for:

    library(ggplot2)
    library(dplyr, warn=FALSE)
    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", space = "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
    }
    
    
    graph_builder(df, values, stage, "Test")