rggplot2

R, ggplot2: How to get same X axis unit scale?


How can I use the same "X axis scale" for multiple plots using R and ggplot2? i.e. given the following two plots, I want the second one to be twice as wide as the first one, as it has twice as many bars (limits can be different, but "unit step" should have same real length, as well as bar size):

enter image description here

Code used to create the plots:

##### set work directory to script directory
getwd()
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
getwd()

##### load libraries
library(ggplot2)
library(patchwork)

##### create dataset 1
gender <- c('M','F','M','F','M','F')
type <- factor(c('A','A','B','B','C','C'))
value <- c(11,22,33,44,55,66)
data1 <- data.frame(gender,type,value)


##### create dataset 2
gender <- c('M','F','M','F','M','F','M','F','M','F','M','F')
type <- factor(c('A','A','B','B','C','C','D','D','E','E','F','F'))
value <- c(1,2,3,4,5,6,7,8,9,10,11,12)
data2 <- data.frame(gender,type,value)

##### create plots
p1 <- ggplot(data = data1, aes(x = type, y = value, fill=gender)) + geom_bar(stat='identity', position='dodge')
p2 <- ggplot(data = data2, aes(x = type, y = value, fill=gender)) + geom_bar(stat='identity', position='dodge')

##### combine plots
p1+p2

Solution

  • We can combine the two tables, noting the source, and then use that source to facet. facet_grid allows you to scale the facets based on the axis of each facet, in this case varying the scale and the physical space on x (hence "free_x").

    ggplot(dplyr::bind_rows(d1 = data1, d2 = data2, .id = "src"),
           aes(x = type, y = value, fill=gender)) +
      geom_col(position='dodge') +
      facet_grid(.~src, scales = "free_x", space = "free_x")
    

    enter image description here