26

Context

I have some datasets/variables and I want to plot them, but I want to do this in a compact way. To do this I want them to share the same y-axis but distinct x-axis and, because of the different distributions, I want one of the x-axis to be log scaled and the other linear scaled.

Example

Suppose I have a long tailed variable (that I want the x-axis to be log-scaled when plotted):

library(PtProcess)
library(ggplot2)

set.seed(1)
lambda <- 1.5
a <- 1
pareto <- rpareto(1000,lambda=lambda,a=a)
x_pareto <- seq(from=min(pareto),to=max(pareto),length=1000)
y_pareto <- 1-ppareto(x_pareto,lambda,a)
df1 <- data.frame(x=x_pareto,cdf=y_pareto)

ggplot(df1,aes(x=x,y=cdf)) + geom_line() + scale_x_log10()

Long tail

And a normal variable:

set.seed(1)
mean <- 3
norm <- rnorm(1000,mean=mean)
x_norm <- seq(from=min(norm),to=max(norm),length=1000)
y_norm <- pnorm(x_norm,mean=mean)
df2 <- data.frame(x=x_norm,cdf=y_norm)

ggplot(df2,aes(x=x,y=cdf)) + geom_line()

Normal

I want to plot them side by side using the same y-axis.

Attempt #1

I can do this with facets, which looks great, but I don't know how to make each x-axis with a different scale (scale_x_log10() makes both of them log scaled):

df1 <- cbind(df1,"pareto")
colnames(df1)[3] <- 'var'
df2 <- cbind(df2,"norm")
colnames(df2)[3] <- 'var'
df <- rbind(df1,df2)

ggplot(df,aes(x=x,y=cdf)) + geom_line() + 
       facet_wrap(~var,scales="free_x") + scale_x_log10()

Facets attempt

Attempt #2

Use grid.arrange, but I don't know how to keep both plot areas with the same aspect ratio:

library(gridExtra)
p1 <- ggplot(df1,aes(x=x,y=cdf)) + geom_line() + scale_x_log10() +
      theme(plot.margin = unit(c(0,0,0,0), "lines"),
            plot.background = element_blank()) +
      ggtitle("pareto")
p2 <- ggplot(df2,aes(x=x,y=cdf)) + geom_line() + 
      theme(axis.text.y = element_blank(), 
            axis.ticks.y = element_blank(), 
            axis.title.y = element_blank(),
            plot.margin = unit(c(0,0,0,0), "lines"),
            plot.background = element_blank()) +
      ggtitle("norm")
grid.arrange(p1,p2,ncol=2)

Grid attempt

PS: The number of plots may vary so I'm not looking for an answer specifically for 2 plots

3
  • 1
    I think your best bet is going to be to use grid.arrange (method #2) and play with the width argument until you get the aspect ratios/plot area widths the same.
    – Ben Bolker
    Commented Feb 7, 2013 at 3:42
  • @João Pesce Can't help you and suspect a lot of fragile kludging might be required but +1 for well-asked and immediately comprehensible question. Commented Feb 7, 2013 at 6:10
  • @João Pesce have you tried removing the plot.marginfrom the theme and see if that makes a difference?
    – Harpal
    Commented Feb 7, 2013 at 11:15

3 Answers 3

12

Extending your attempt #2, gtable might be able to help you out. If the margins are the same in the two charts, then the only widths that change in the two plots (I think) are the spaces taken by the y-axis tick mark labels and axis text, which in turn changes the widths of the panels. Using code from here, the spaces taken by the axis text should be the same, thus the widths of the two panel areas should be the same, and thus the aspect ratios should be the same. However, the result (no margin to the right) does not look pretty. So I've added a little margin to the right of p2, then taken away the same amount to the left of p2. Similarly for p1: I've added a little to the left but taken away the same amount to the right.

library(PtProcess)
library(ggplot2)
library(gtable)
library(grid)
library(gridExtra)

set.seed(1)
lambda <- 1.5
a <- 1
pareto <- rpareto(1000,lambda=lambda,a=a)
x_pareto <- seq(from=min(pareto),to=max(pareto),length=1000)
y_pareto <- 1-ppareto(x_pareto,lambda,a)
df1 <- data.frame(x=x_pareto,cdf=y_pareto)

set.seed(1)
mean <- 3
norm <- rnorm(1000,mean=mean)
x_norm <- seq(from=min(norm),to=max(norm),length=1000)
y_norm <- pnorm(x_norm,mean=mean)
df2 <- data.frame(x=x_norm,cdf=y_norm)

p1 <- ggplot(df1,aes(x=x,y=cdf)) + geom_line() + scale_x_log10() +
      theme(plot.margin = unit(c(0,-.5,0,.5), "lines"),
            plot.background = element_blank()) +
      ggtitle("pareto")
p2 <- ggplot(df2,aes(x=x,y=cdf)) + geom_line() + 
      theme(axis.text.y = element_blank(), 
            axis.ticks.y = element_blank(), 
            axis.title.y = element_blank(),
            plot.margin = unit(c(0,1,0,-1), "lines"),
            plot.background = element_blank()) +
      ggtitle("norm")

gt1 <- ggplotGrob(p1)
gt2 <- ggplotGrob(p2)

newWidth = unit.pmax(gt1$widths[2:3], gt2$widths[2:3])

gt1$widths[2:3] = as.list(newWidth)
gt2$widths[2:3] = as.list(newWidth)

grid.arrange(gt1, gt2, ncol=2)

enter image description here

EDIT To add a third plot to the right, we need to take more control over the plotting canvas. One solution is to create a new gtable that contains space for the three plots and an additional space for a right margin. Here, I let the margins in the plots take care of the spacing between the plots.

p1 <- ggplot(df1,aes(x=x,y=cdf)) + geom_line() + scale_x_log10() +
      theme(plot.margin = unit(c(0,-2,0,0), "lines"),
            plot.background = element_blank()) +
      ggtitle("pareto")
p2 <- ggplot(df2,aes(x=x,y=cdf)) + geom_line() + 
      theme(axis.text.y = element_blank(), 
            axis.ticks.y = element_blank(), 
            axis.title.y = element_blank(),
            plot.margin = unit(c(0,-2,0,0), "lines"),
            plot.background = element_blank()) +
      ggtitle("norm")

gt1 <- ggplotGrob(p1)
gt2 <- ggplotGrob(p2)

newWidth = unit.pmax(gt1$widths[2:3], gt2$widths[2:3])

gt1$widths[2:3] = as.list(newWidth)
gt2$widths[2:3] = as.list(newWidth)

 # New gtable with space for the three plots plus a right-hand margin
gt = gtable(widths = unit(c(1, 1, 1, .3), "null"), height = unit(1, "null"))

# Instert gt1, gt2 and gt2 into the new gtable
gt <- gtable_add_grob(gt, gt1, 1, 1)
gt <- gtable_add_grob(gt, gt2, 1, 2)
gt <- gtable_add_grob(gt, gt2, 1, 3)

grid.newpage()
grid.draw(gt)

enter image description here

3
  • Nice, but how would you do it for 3 plots so they are the same size and evenly (but not overly) spaced? eg: grid.arrange(gt1, gt2, gt2, ncol=3). Commented Feb 7, 2013 at 15:42
  • @JoãoPesce I would stick to the gtable theme, but in place of grid.arrange(), create a new gtable with space for the three plots plus a right hand margin. See the edit. Commented Feb 7, 2013 at 20:27
  • I think this may need to be updated for newer versions of R. As of version 4.0.1 run in RStudio v. 1.3.959, when I copy and paste the code for two plots exactly as above (either directly in RStudio, or by creating an external window with something like dev.new(width=6, height=4, noRStudioGD=T)), there are various issues: plots and x-axis meld into one another (there is no vertical white space between plots), titles are not centered. This also occurs if I plot it directly in R (v. 4.0.1), not RStudio.
    – Meg
    Commented Jun 17, 2020 at 14:46
10

The accepted answer is exactly what makes people run when comes to plotting using R! This is my solution:

library('grid')
g1 <- ggplot(...)  # however you draw your 1st plot
g2 <- ggplot(...)  # however you draw your 2nd plot
grid.newpage()
grid.draw(cbind(ggplotGrob(g1), ggplotGrob(g2), size = "last"))

This takes care of the y axis (minor and major) guide-lines to align in multiple plots, effortlessly.

Dropping some axis text, unifying the legends, ..., are other tasks that can be taken care of while creating the individual plots, or by using other means provided by grid or gridExtra packages.

1
  • 3
    This option did not work for me. Y-axis keep floating.
    – Laura
    Commented May 29, 2020 at 14:09
1

The accepted answer looks a little too daunting to me. So I find two ways to get around it with less efforts. Both are based on your Attempt #2 grid.arrange() method.

1. Make plot 1 no y-axis as well
theme(axis.text.y = element_blank(), 
      axis.ticks.y = element_blank(), 
      axis.title.y = element_blank()

So all the plots will be the same. You won't have problems with different aspects ratios. You will need to generate a separate y-axis with R or your favorite image editting app.

2. Fix and respect aspects ratio

Add aspect.ratio = 1 or whatever ratio you desire to theme() of individual plots. Then use respect=TRUE in your grid.arrange()

This way you can keep y-axis in plot1 and still maintains aspects ratio in all plots. Inspired by this answer.

Hope you find these helpful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.