3
votes

I want to make three plots in one graph with a title and only one x label, but when I modify the margins to include these labels the plots end up with different sizes.

This is what I tried:

par(mfrow=c(3,1), mar=c(1.5,5,3,2) + 0.1)
plot(1:10, xaxt='n', main = "Some title")

par(mar=c(1.5,5,0,2) + 0.1)
plot(1:10, xaxt='n')

par(mar=c(5,5,0,2) + 0.1)
plot(1:10, xlab = "Some x label")

And the plots looks like this:

http://i.stack.imgur.com/W0Rl6.png

As you can see the second plot has a different size. What I want is that all end up having the same size.

Any help would be really appreciated!

2
Just came across this question... turns out it's quite similar to my own question from a while later which has some different answers. I use par(mar = c(0,0,0,0), oma = c(5.1,4.1,4.1,2.1)) all the time!MichaelChirico

2 Answers

1
votes

This isn't super easy to do with base graphics. The problem is that while mfrow splits the split device into three rows, the title of the first plot and the x axis label of the last take up room in each of their respective rows. The would be easier using Lattice or ggplot. To use these functions you generally want to have all your data in a single data.frame before you begin. For example, with this test data set

dd<-data.frame(x=rep(1:10,3),y=rep(1:10,3), group=rep(1:3, each=10))

you can use ggplot2

library(ggplot2)
ggplot(dd, aes(x,y)) + 
    geom_point() + 
    facet_grid(group~.) + 
    ggtitle("Some title") + xlab("Some X label")

enter image description here

or Lattice

library(lattice)
xyplot(y~x|factor(group), dd, layout=c(1,3), 
    main="Some Title", xlab="Some X label")

enter image description here

1
votes

You can use the layout function. To plot the above, make a layout for 5 graphs: a top narrow one which will serve as space for the title, followed by the 3 scatter plots, and a fifth narrow graph, for the x-label at the bottom.

Margins eg:

par(mar=c(0.5,6,0.5,2)+0.1)

Make a matrix specifying the plot layout: mat<-matrix(c(1:5),5,1, byrow=T)

The layout function including widths and heights. Here, we only have one column of plots, so there is just one width, and then the heights for each row of plots:

layout(mat, widths=1, heights= c(0.5, 3, 3, 3, 1.5))

The first plot will be a blank plot

plot(0, xaxt='n', yaxt='n', bty='n', pch='', ylab='', xlab='')

Plot the scatter plots and add texts for the titles and axis labels. Note the "padj" in the text function may need to be modified in accordance with the size of your Quartz window. The last plot is also empty

plot(1:10, xaxt='n')
mtext("Some title", 1, padj=-15)
plot(1:10, xaxt='n')
mtext("Some ylabel", 2, padj=-5)
plot(1:10)
mtext("Some x label",  padj=20)
plot(0, xaxt='n', yaxt='n', bty='n', pch='', ylab='', xlab='')