R: Changing Trellis graphics settings – remove margins

18Dec08

My aim was to produce a tiny histogram as a png output. I want to use these tiny histograms to put them into a table, so the distribution of a variable can be assessed at an instance and be compared to others right away.

To produce such a graphic in the base graphic system is quite easy. Note that I use the function MHmakeRandomString (described in former posting) to generate a random name for the picture.

###############################################################

# basic information about output directory
OutputDirRelative <- "output"

# combine the working directory with output path
OutputDir <- paste(getwd(), OutputDirRelative, sep="/")

# function that generates random string (12 characters)    
randomName <- MHmakeRandomString()
filename <- paste(OutputDir, "/", randomName, ".png", sep="") 

# open png device
png(filename = filename, res= 72, width= 35, height= 18)
     par(mar=c(0,0,0,0), oma=c(0,0,0,0))
     hist(data , main="", col=col)
     box()

dev.off()

###############################################################
base

base

This produces a histogram with no annotation or margins at all. Now I wanted the same but implemented in the grid graphics system. It caused me some trouble to remove the margins until some experts from the r-help list helped me out.


###############################################################


randomName <- MHmakeRandomString()
filename <- paste(OutputDir, "/", randomName, ".png", sep="") 

# open png device
png(filename = filename, res= 72, width= 35, height= 18)x <- rnorm(100)
    limits <- prepanel.default.histogram(x, breaks = NULL) ##
    # to start a new page 
    grid.newpage()
    pushViewport(viewport(xscale = extendrange(limits$xlim),
                          yscale = extendrange(limits$ylim)))
                          panel.histogram(x, breaks = NULL)
dev.off()

###############################################################
grid

grid

A tiny histogram produces by grid/trellis graphics. Nice!




%d bloggers like this: