January
January

Reputation: 17090

Combining two plots side by side

I need to put two plots side by side. As such, not a hard exercise, except that:

  1. I want and need to use basic graphics
  2. the plots should be placed seamlessly next to each other.

Here is an example how I solve it

x2 <- seq(1.9, 7.3, length.out=10)
x1 <- seq(0.2, 5.8, length.out=10)
y1 <- rnorm(10)
par(mfrow=c(1,2))
par(mar=c(5,4,4,0))
plot(x1, y1, type="l", bty="n", xlim=range(x1), ylim=c(-2, 2))
par(mar=c(5,0,4,2))
plot(x2, y1, type="l", bty="n", xlim=rev(range(x2)), ylim=c(-2, 2), yaxt="n")

enter image description here

Here is the problem: I would like the two lines to touch or almost touch. If the axes are separated, that is OK; but the distance between these two plots should be minimal. Optimally, I will want to have fat red vertical line showing where the two parts of the plot meet.

None of the answers I have found so far allow me to do that.

Context: I am plotting a genomic rearrangement in which two distant parts of some chromosomes were fused together, one of them reversed (hence the different scaling).

Upvotes: 2

Views: 1465

Answers (2)

Ian Campbell
Ian Campbell

Reputation: 24790

While @DarrenTsai's answer is absolutely correct, you'll find that the x-axis scales take up different values per pixel when they have different mar parameters. I suggest you consider plotting them together and then adding a custom axis.

x2 <- seq(1.9, 7.3, length.out=10)
x1 <- seq(0.2, 5.8, length.out=10)
y1 <- rnorm(10)
ValueTable <- data.frame(Foward = c(x1,max(x1) + (x2-min(x2))), Join = c(x1,rev(x2)))
plot(ValueTable$Foward,c(y1,rev(y1)),type = "l",xaxt="n",xlab = "",ylab = "Value")
axis(1, ValueTable$Foward[seq(1,nrow(ValueTable),by = 2)], labels=formatC(ValueTable$Join[seq(1,nrow(ValueTable),by = 2)],format = "f", digits = 2))
abline(v=max(x1))

enter image description here

Upvotes: 2

Darren Tsai
Darren Tsai

Reputation: 35554

Add xaxs = "i" into the fist par(), i.e.

par(mfrow = c(1, 2), xaxs = "i")

and run the entire code again.

xaxs indicates the style of axis interval calculation to be used for the x-axis. The default is "r"(regular) which extends the data range by 4 percent at each end. Revising it to "i" will make the x-axis fit within the original data range.

enter image description here

Upvotes: 2

Related Questions