Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Two plot side by side using base R plots, with shared titel and shared x-axis label

I’m trying to plot two plots side by side using base R.

I’d like them to share the title and the x-axis and y-axis label.
However, the range of the plots is different, so I want to keep the number of the labels.

I’ve seen that there are some solutions using par(), however, they seem overly complex.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried the following solution using layout():

dev.off()
# Create a layout with two plots

layout(matrix(c(1, 2), nrow = 1))

# Create the first plot
plot(1:10, 1:10, main = "Plot 1", type = "l", col = "blue", xlab = "")

# Create the second plot without the x-axis
plot(1:10, (1:10)^2, main = "", type = "l", col = "red", xlab = "")

# Draw the x-axis in the middle of the two plots
axis(side = 1, at = 5, labels = FALSE)

# Add labels to the x-axis if needed
mtext("Common X-axis Label", side = 1, line = 2)

# Reset the layout
layout(1)

However I cant get the x-axis label and the main title to the center of the plot?
Any ideas on how to do this?

I’ve tried to use the line = 2 to put the x-axis label in the center of the two plots.

Now it looks like this:

enter image description here

>Solution :

It’s not overly complex. I think you are looking for

mtext("My Multiplot Title", side = 3, line = -2, outer = TRUE)
mtext("Common X-axis Label", side = 1, line = -2, outer = TRUE)

outer = TRUE does the trick.

With

layout(matrix(c(1, 2), nrow = 1))

# Create the first plot
plot(1:10, 1:10, main = "", type = "l", col = "blue", xlab = "")

# Create the second plot 
plot(1:10, (1:10)^2, main = "", type = "l", col = "red", xlab = "")

Created on 2023-10-18 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading