Tuesday, February 26, 2013

Exporting nice plots in R

from:http://www.r-bloggers.com/exporting-nice-plots-in-r/?utm_source=feedburner&utm_medium=email&utm_campaign=Feed%3A+RBloggers+%28R+bloggers%29


The Cairo-package

The Cario package is an excellent choice for getting antia-aliased plots in Windows. Here’s the same plot from the Cairo package (the background is now transparent):
?View Code RSPLUS
1
2
3
4
5
6
7
8
9
10
library(Cairo)
Cairo(file="Cairo_PNG_72_dpi.png", 
      type="png",
      units="in", 
      width=5, 
      height=4, 
      pointsize=12, 
      dpi=72)
my_sc_plot(data)
dev.off()

If we want to increase the resolution of the plot we can’t just change the resolution parameter:
?View Code RSPLUS
1
2
3
4
5
6
7
8
9
Cairo(file="Cairo_PNG_96_dpi.png", 
      type="png",
      units="in", 
      width=5, 
      height=4, 
      pointsize=12, 
      dpi=96)
my_sc_plot(data)
dev.off()

We also have to change the point size, the formula is size * new resolution DPI / 72 DPI:
?View Code RSPLUS
1
2
3
4
5
6
7
8
9
Cairo(file="Cairo_PNG_96_dpi_adj.png", 
      type="png",
      units="in", 
      width=5, 
      height=4, 
      pointsize=12*92/72, 
      dpi=96)
my_sc_plot(data)
dev.off()
Adjusted point size results in the labels remaining the proper sizeIf we double the image size we also need to double the point size:
?View Code RSPLUS
1
2
3
4
5
6
7
8
9
Cairo(file="Cairo_PNG_72_dpi_x_2.png", 
      type="png",
      units="in", 
      width=5*2, 
      height=4*2, 
      pointsize=12*2, 
      dpi=72)
my_sc_plot(data)
dev.off()

 If you want the background to be white just add the bg parameter:
?View Code RSPLUS
1
2
3
4
5
6
7
8
9
10
Cairo(file="Cairo_PNG_72_dpi_white.png", 
      bg="white",
      type="png",
      units="in", 
      width=5, 
      height=4, 
      pointsize=12, 
      dpi=72)
my_sc_plot(data)
dev.off()

Here’s the plot code:
?View Code RSPLUS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Create the data
data <- rnorm(100, sd=15)+1:100
# Create a simple scatterplot
# with long labels to enhance 
# size comparison
my_sc_plot <- function(data){
  par(cex.lab=1.5, cex.main=2)
  plot(data, 
       main="A simple scatterplot", 
       xlab="A random variable plotted", 
       ylab="Some rnorm value",
       col="steelblue")
  x <- 1:100
  abline(lm(data~x), lwd=2)
}

No comments:

Post a Comment