Search code examples
rggplot2axis-labels

ggplot: adjust axis space according to months


Updated:

How can I modify the following ggplot to get the following:

  1. X axis should be adjusted for months i.e. baseline to 6 months should be shorter, 6 months to 24 months should be longer depending on the number of months in between the time points. (solution below)

  2. Include a break (say at 36 months) in X axis between 24 months to 48 months.

  3. Make the plot larger by reducing the white space before baseline and after 48 months. (solution below)

Thanks for your help!

fat <- structure(list(study_group = structure(c(1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L), .Label = c("Intervention group", "Control group"
), class = "factor"), mean1 = c(37.02, 32.95, 34.18, 36.38, 37.1, 
37.27, 37.64, 38.22), se1 = c(0.22, 0.3, 0.35, 0.38, 0.23, 0.35, 
0.28, 0.32), timepoint1 = c(0, 6, 24, 48, 0, 6, 24, 48)), row.names = c(3L, 
7L, 11L, 15L, 19L, 23L, 27L, 31L), class = "data.frame")


ggplot(fat, aes(timepoint1, mean1, colour = study_group)) +
  geom_point(size=2) + 
  geom_line(size=1.2) +
  geom_errorbar(aes(ymin=mean1-se1, ymax=mean1+se1), width=1, size=1) + 
  scale_x_continuous(
    breaks = c(0, 6, 24, 36, 48),
    labels = c("Baseline", "6 months", "24 months", "36 months", "48 months"),
    expand = c(0.05, 0))

enter image description here


Solution

  • Probably your best bet is to encode the number of months as a numeric vector instead of a factor/character. You can then set the breaks and re-label the x-axis. The whitespace on either side is controlled by the scale's expand parameter. Example with dummy data below:

    library(ggplot2)
    #> Warning: package 'ggplot2' was built under R version 4.0.3
    
    df <- data.frame(
      x = rep(c(0, 6, 24, 48), 2), # <- encode as numeric
      ymin = c(1,2,3,4,1,3,5,7),
      y = c(2,3,4,5,2,4,6,8),
      ymax = c(3,4,5,6,5,7,8,9),
      group = rep(c("A", "B"), each = 4)
    )
    
    ggplot(df, aes(x, y, colour = group)) +
      geom_line() +
      geom_errorbar(aes(ymin = ymin, ymax = ymax)) +
      # Details for the x-axis
      scale_x_continuous(
        breaks = c(0, 6, 24, 36, 48),
        labels = c("Baseline", "6 months", "24 months", "36 months", "48 months"),
        expand = c(0.02, 0)
      )
    

    As a suggestion for asking questions on SO, try to include some relevant (dummy) data and omit code not relevant for the question at hand (e.g. theme settings, y scales, decorations etc.). This makes it easier to get to the core of the question without being distracted by extra code or having to generate dummy data.