Producing heatmap using geom_raster() makes different results in PDF and display
I am trying to produce heatmap using geom_raster() of ggplot2. Here is the code:
foo <- matrix(1:999,ncol=3) ggplot(melt(foo), aes(X2,X1, fill=value)) + geom_raster()
The result is:
But the result is so different while casting the output to a PDF file (using pdf() function):
There are many columns, with colors gradually changing between the columns. How to have the same heatmap as the first one while casting the output to PDF file?
Some pdf viewers don't manage properly the output of grid.raster, even with interpolate=FALSE they insist on showing some spurious gradient. Your pdf most probably is good (as per the pdf format specifications), it's the pdf viewer that is deficient (overzealous to smooth).
Try to see if you have some preferences in the viewer to turn off interpolation and/or a different pdf viewer, e.g. in Mac's Preview application, one can switch "smooth text and line art" off and see the expected output. There's a similar option in the cross-platform Adobe Reader.