2

I have a multiple plot and I want to print it on an A4 pdf page so that the charts fill the whole page. When I used the code below I got a lot of blank space above and below the charts. How can I reduce this blank space to about 1cm and increase the chart height? Thank you for your help.

group <- "Title"
layout(matrix(c(1:12), 6, 2) )
par(mar = c(0, 4.1, 1.5, 2.1),oma = c(2, 0, 2, 0)) 
plot(1:10)
plot(1:10)
plot(1:10)
plot(1:10)
plot(1:10)
plot(1:10)
plot(1:10)
plot(1:10)
plot(1:10)
plot(1:10)
plot(1:10)
plot(1:10)

mtext(group, outer = TRUE, cex = 1.5)
mtext("text", outer = TRUE,side =1)
dev.print(pdf, file="charts12.pdf" ,onefile=T,paper='A4') 
adam.888
  • 7,686
  • 17
  • 70
  • 105

2 Answers2

5

Changing from dev.print to simply pdf allows you specify the width and height of the device. The units used are inches, so A4 is 8.27" X 11.69". I have added an example below. I had to adjust the top margin around the chart for this example.

data("mtcars")
pdf("test.pdf", width = 8.27, height = 11.69)
group <- "Title"
layout(matrix(c(1:12), 6, 2) )
par(mar = c(0, 4.1,2.5, 2.1),oma = c(2, 0, 2, 0))
plot(mtcars$mpg ~ mtcars$hp)
plot(mtcars$mpg ~ mtcars$hp)
plot(mtcars$mpg ~ mtcars$hp)
plot(mtcars$mpg ~ mtcars$hp)
plot(mtcars$mpg ~ mtcars$hp)
plot(mtcars$mpg ~ mtcars$hp)
plot(mtcars$mpg ~ mtcars$hp)
plot(mtcars$mpg ~ mtcars$hp)
plot(mtcars$mpg ~ mtcars$hp)
plot(mtcars$mpg ~ mtcars$hp)
plot(mtcars$mpg ~ mtcars$hp)
plot(mtcars$mpg ~ mtcars$hp)
mtext(group, outer = TRUE, cex = 1.5)
mtext("text", outer = TRUE,side =1)
dev.off()
amwill04
  • 1,330
  • 1
  • 11
  • 18
5

dev.print "copies the graphics contents of the current device to a new device" (from ?dev.pront) which means that the proportions of the output graphic depends on how the source device has been scaled. Resizing the plot window affects the amount of whitespace you get.

If you additionally specify width and height you can fit the plot to A4, making the result independent of the plot window.

dev.print(pdf, file="charts12.pdf" ,onefile=T,paper='A4', width = 21/2.54, height = 29.7/2.54) 

I divided width and height by 2.54 to convert the centimeter to inches.

Using pdf() and dev.off() as in the answer by @amwill04 also works but has the disadvantage that you do not see the plot before it is written to the file. While this should not matter with production code it may make writing the code that produces the graph easier because simply sourceing the code produces a preview of the graph.

CL.
  • 14,577
  • 5
  • 46
  • 73
  • Thanks for pointing that out. Only ever used my method so interesting to hear its as simple as specifying the `height` and `width` – amwill04 Oct 26 '15 at 12:40