Soheil
Soheil

Reputation: 333

How to create a multiple plots having same X axis?

I am trying to make a single plot using dataset with same X axis but different Y axis. As an example, I have this dataset:

A1 <- rnorm(100)
B1 <- rnorm(100)
B2 <- rnorm(100)
B3 <- rnorm(100)

grid <- matrix(c(1:3),nrow=3,ncol=1,byrow=TRUE)
layout(grid)

plot(A1,B1)
plot(A1,B2)
plot(A1,B3)

This is what I get and comes with multiple X axis:

enter image description here

I know how to do it using ggplot2 but I am looking for another way like using layout. Any help would be much appreciated.

Upvotes: 1

Views: 7178

Answers (2)

Soheil
Soheil

Reputation: 333

Its too easy by working with par(mar) and layout function.

par(mar=c(6,6,4,4))
layout(matrix(1:3, ncol = 1), widths = 1, heights = c(2.3,2,2.3), respect = FALSE)
par(mar = c(0, 4.1, 4.1, 2.1))
plot(B1,A1,xaxt='n')
par(mar = c(0, 4.1, 0, 2.1))
plot(B2,A1,xaxt='n')
par(mar = c(4.1, 4.1, 0, 2.1))
plot(B3,A1)

enter image description here

Upvotes: 1

Benjamin Christoffersen
Benjamin Christoffersen

Reputation: 4841

You can

  1. Use the mfcol argument in par to set the number of plots, use mar to leave out the margins, oma to add space to axis which you will make with axis, and mgp to set the space for the axis label you will make.
  2. Make the plots without axis with axes = FALSE.
  3. Use box to add the boxes around the plots.
  4. Add the axis labels in the end with mtext.

Here is an example

set.seed(32273438)
A1 <- rnorm(100)
B1 <- rnorm(100)
B2 <- rnorm(100)
B3 <- rnorm(100)

par(mfcol = c(3, 1), mar = numeric(4), oma = c(4, 4, .5, .5), 
    mgp = c(2, .6, 0))
plot(A1, B1, axes = FALSE)
axis(2L)
box()
plot(A1, B2, axes = FALSE)
axis(2L)
box()
plot(A1, B3, axes = FALSE)
axis(1L)
axis(2L)
box()
mtext("A1", side = 1, outer = TRUE, line = 2.2)
mtext("B", side = 2, outer = TRUE, line = 2.2)

enter image description here

You may have issues with overlapping y-ticks but you solve this with a the yaxp argument of par.

Upvotes: 5

Related Questions