Search code examples
rggplot2alignmentaxis-labelscowplot

Axis title alignment with mixed multiple graphs in R


I'm using ggplot2 package to make my graphs. I have 2 graphs, that I mixed using plot_grid() from cowplot package.

library(ggplot2)
library(cowplot)

x1 <- c(52.67, 46.80, 41.74, 40.45)
y1 <- c(1.726219351, 1.842421805, 1.790801758, 1.449997494)
x2 <- c(51.07, 65.97, 61.01, 49.25)
y2 <- c(5.39765063, 0.215293169, 0.694595893, 1.501089083)

DF <- data.frame(x1, y1, x2, y2)

p1 <- ggplot(DF, aes(x1, y1)) + 
  geom_point() +
  theme(aspect.ratio = 1)

p2 <- ggplot(DF, aes(x2, y2)) + 
  geom_point() +
  theme(aspect.ratio = 1)

plot_grid(p1, p2)

plot_grid(p1, p2, align = "hv")

The y axis of the second graph (p2) is larger than the y axis of the plot p1 (red line in the image), só I used align, from the cowplot package. However, the y axis label stays in the same position as the original plot (p2) size (blue line in the image). Is there a way to make the label to stand near to the y axis as the original plot?

enter image description here


Solution

  • Alignment of graphs with fixed axis ratio can be difficult. In any case, if you use the axis argument in addition to align things work. For more details, see here: https://wilkelab.org/cowplot/articles/aligning_plots.html

    library(ggplot2)
    library(cowplot)
    #> 
    #> ********************************************************
    #> Note: As of version 1.0.0, cowplot does not change the
    #>   default ggplot2 theme anymore. To recover the previous
    #>   behavior, execute:
    #>   theme_set(theme_cowplot())
    #> ********************************************************
    
    x1 <- c(52.67, 46.80, 41.74, 40.45)
    y1 <- c(1.726219351, 1.842421805, 1.790801758, 1.449997494)
    x2 <- c(51.07, 65.97, 61.01, 49.25)
    y2 <- c(5.39765063, 0.215293169, 0.694595893, 1.501089083)
    
    DF <- data.frame(x1, y1, x2, y2)
    
    p1 <- ggplot(DF, aes(x1, y1)) + 
      geom_point() +
      theme(aspect.ratio = 1)
    
    p2 <- ggplot(DF, aes(x2, y2)) + 
      geom_point() +
      theme(aspect.ratio = 1)
    
    plot_grid(p1, p2, align = "hv", axis = "tbrl")
    

    Created on 2019-07-26 by the reprex package (v0.3.0)