Search code examples
rggplot2facetfacet-grid

How to create Facet Grid based on condition using ggplot in R?


This question is extension of this question. Basically, I am trying to plot frequency distribution of systems in facets based on locations using below code. The current issues is that I am able to plot the frequency on the plot, but x-axis is showing all the systems in Loc1, which is False, because Loc1 only contains Sys1 and Sys2. My question is Is there a way to modify/update x-axis based on Locations? So for Loc1, only frequency count of "Sys1" and "Sys2" will show. For "Loc2" it will be "Sys3", "Sys4", and for "Loc3" it will be only "Sys6".

Provide explanation with code

Dataset

structure(list(Systems = c("Sys1", "Sys2", "Sys3", "Sys4", "Sys6"
), Locations = c("loc1", "loc1", "loc2", "loc2", "loc3"), frequency = c(2L, 
1L, 1L, 1L, 0L)), row.names = c(NA, -5L), class = "data.frame")

Code for plotting

ggplot(d,aes(Systems,frequency))+geom_col()+facet_grid(.~Locations)

Solution

  • According to ?facet_grid,

    scales - Are scales shared across all facets (the default, "fixed"), or do they vary across rows ("free_x"), columns ("free_y"), or both rows and columns ("free")?

    space - If "fixed", the default, all panels have the same size. If "free_y" their height will be proportional to the length of the y scale; if "free_x" their width will be proportional to the length of the x scale; or if "free" both height and width will vary. This setting has no effect unless the appropriate scales also vary.

    So, we can change thee default option of scales and space from "fixed" to "free_x" in facet_grid

    library(ggplot2) 
    ggplot(d, aes(Systems,frequency)) +
          geom_col()+
          facet_grid(.~Locations, space= "free_x", scales = "free_x")
    

    enter image description here