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')
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With