2
votes

I'm trying to do something ostensibly simple: create a heatmap (i.e. 2D histogram) image with specified pixel-by-pixel dimensions (3600x3600) with no margins or axis labels whatsoever.

I can successfully create a matrix of my data using the hist2d function. However, when I plot using the following code, I get an image file that is indeed 3600x3600 but actually includes x- and y-axis tickmarks and some whitespace on the edges. Annoyingly, this whitespace is not isotropic -- there are different amounts on different sides -- so I can't just make the initial image a bit larger, read it into PhotoShop, and clip it down to 3600x3600 so as to encompass just the plot area pixels (laborious though that would be).

par(mar=c(0,0,0,0)) # this *should* eliminate all margins, leaving only the plot area... right?
png("filename.png", w=3600, h=3600)
image(my_matrix, col=heat.colors(16))
dev.off()

Strangely, those labels and whitespace do not appear if I just plot the image in a Quartz window (I'm on a MacBook Pro, FYI):

image(my_matrix, col=heat.colors(16)) # opens new window that looks perfect!

This would work fine, but there's no way (that I know of) to specify this plot's size in pixels, just in inches (via pin). So I can't just save out this plot window to get the exact PNG I want.

I've spent several days on this already and am getting nowhere. Any help? Is there some weirdness with how the par(mar) parameter interacts with certain plotting "devices" or something?...

2
We had a nice discussion about heatmaps and other strategies to display correlation structures here: stackoverflow.com/questions/7597216/…Matt Bannert

2 Answers

5
votes

If I put the par call after the device activation, it works (along with setting axes = FALSE to get rid of the axes:

png("~/Desktop/so/heatmap.png",w=400,h=400)
par(mar = c(0,0,0,0))
require(grDevices) # for colours
x <- y <- seq(-4*pi, 4*pi, len=27)
r <- sqrt(outer(x^2, y^2, "+"))
image(z = z <- cos(r^2)*exp(-r/6), col=gray((0:32)/32),axes = FALSE)
dev.off()

enter image description here

Obviously, I used smaller image dimensions in this example. This example code is from ?image.

1
votes

Do the par(mar=c(0,0,0,0)) after the call to png rather than before.