简体   繁体   中英

Create R heatmap with no margins whatsoever

I'm trying to do something ostensibly simple: create a heatmap (ie 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?...

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()

在此处输入图片说明

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

在调用png而不是之前执行par(mar=c(0,0,0,0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM