pdf of figure in R has unsightly white lines in it - r

I'm trying to make colorbars, as well as raster maps, in R, and the output figures give unsightly lines in them when exported to pdf.
Here is code to generate a colorbar. It looks fine when you run it in R:
color.bar <- function(lut, min, max=-min, nticks=11, ticks=seq(min, max, len=nticks), title='') {
scale = (length(lut)-1)/(max-min)
plot(c(0,10), c(min,max), type='n', bty='n', xaxt='n', xlab='', yaxt='n', ylab='', main=title)
axis(4, ticks, las=1)
for (i in 1:(length(lut)-1)) {
y = (i-1)/scale + min
rect(0,y,10,y+1/scale, col=lut[i], border=NA)
}
}
par(mfrow=c(2,1))
par(mar=c(3,0,3,2.5))
pal = colorRampPalette(c("red","yellow"))
neg = pal(100)
pal = colorRampPalette(c("yellow","darkgreen"))
pos = pal(50)
color.bar(c(neg,pos),min=-75,max=50,ticks=c(-75,-50,-25,0,25,50))
color.bar(colorRampPalette(c("goldenrod","blue"))(25),min=0,max=1)
par(mar=c(5.1,4.1,4.1,2.1))
dev.copy2pdf(file = "colorbar_wood.pdf", height = 8, width = 1)
pdf("colorbar_wood.pdf",width=1,height=8)
par(mfrow=c(2,1))
par(mar=c(3,0,3,2.5))
pal = colorRampPalette(c("red","yellow"))
neg = pal(100)
pal = colorRampPalette(c("yellow","darkgreen"))
pos = pal(50)
color.bar(c(neg,pos),min=-75,max=50,ticks=c(-75,-50,-25,0,25,50))
color.bar(colorRampPalette(c("goldenrod","blue"))(25),min=0,max=1)
par(mar=c(5.1,4.1,4.1,2.1))
dev.off()
And here is what I get out as a pdf:
link
I need to get this up to publication quality. Any ideas on how to fix?

This is invariably an issue with the software used to render the PDF, not with R, and arises because of features such as anti-aliasing and other rendering operations that the PDF Viewer does in order to display the PDF.
This is discussed in ?pdf, notably
Note:
If you see problems with PDF output, do remember that the problem
is much more likely to be in your viewer than in R. Try another
viewer if possible. Symptoms for which the viewer has been at
fault are apparent grids on image plots (turn off graphics
anti-aliasing in your viewer if you can) and missing or incorrect
glyphs in text (viewers silently doing font substitution).
Unfortunately the default viewers on most Linux and Mac OS X
systems have these problems, and no obvious way to turn off
graphics anti-aliasing.
....
I just viewed your PDF in two different PDF viewers on Linux (Evince and Okular) and the degree to which these artefacts affected the file was different across the two viewers, with Okular giving fewer artefacts on the red-green one and none on the blue-yellow one. As such this seems to be an issue with viewing the PDF and not something with R. Your figure should therefore be publication quality.

Related

How to enhance resolution of ggairs plot when ggsave not working

I'm trying to save a rather large ggpairs file. For some reason I can't get ggsave to work on my device (the file is created but it's blank no matter the plot, file type etc.) so I have been manually right clicking on save image as on the output.
However the resolution is so poor you can't read the correlation information as I've had to reduce the font size.
Appreciate any suggestions on how to get out a readable output.
TIPI_data<- vms_data[, c("cond","group_aff","personal_exp","outcomes","mechanics", "TIPI_O", "TIPI_C", "TIPI_E","TIPI_A","TIPI_N")]
ggpairs(TIPI_data, ggplot2::aes(colour=cond), upper = list(continuous = wrap("cor", size = 1.5)))
I don't know if this works for you, it worked for me. I have used this code to save as png with high resolution:
corrPlot <- ggpairs(df, diag=list(continuous="density"), axisLabels='show')
png(filename, height=1000, width=1000)
print(corrPlot)
dev.off()
I used this reference: https://github.com/tidyverse/ggplot2/issues/650#issuecomment-65086626

odd appearance of colors with viridis in PDFs viewed by Preview v. Adobe

I've been creating heatmaps using heatmap.2() in R.
I'm using the viridis() color scale.
I used pdf() to create the output.
As you can see the color key looks different when viewing the PDF file using Adobe Acrobat (top panel) v. using Preview (bottom panel) in OS X (version 11.3.1). The Adobe Acrobat appearance is closer to what I expect. The colors in Preview appear washed out and undersaturated.
Has anyone else had this experience?
Code added after original post:
The following code generates the "washed out" color key in the heatmap:
library ('viridis')
library('gplots')
test.matrix <- matrix(ncol=25, nrow=9, -4:4)
breaks <- seq(-4,4,0.5)
pdf(file='heatmap.pdf', width=10, height=6)
heatmap.2(test.matrix, density.info = 'none', trace='none',
Colv = F, Rowv = F, dendrogram = 'none',
col=viridis(length(breaks)-1), breaks=breaks
)
dev.off()
Adobe Reader (default settings) does not display plots exactly as they are stored in the file. You can play around with the settings at Edit > Preferences > Page Display. Try to open the file with another PDF reader and you probably see a difference. The Adobe program also makes thin lines appear thicker, smoothes low resolution images, fills gaps between nearby lines etc.
Visual comment - not an answer for bounty.
As per Jon-Spring comment above.
It is not a difference per app as such, here is the exact same input file with colour profiles toggled on and off on the same screen. Note my simulation unlike the OP affects the Pixelated Text. I am using an RGB image from 1st example above rather than Coloured Objects However it shows the underlying difference.
I would thus suggest looking for any colour profile related settings in Preview

embedFonts is changing the bounding box of my R plot

I have made a beautiful plot in R to be used in a scientific journal. According to the journal's specifications, I need an eps file format with embedded fonts. Since R does not export eps files with embedded fonts, I am using the base graphics call embedFonts() to convert it. However, this call is changing the bounding box of my figure. In this simple example below, the white space is cropped. In my OCD-adjusted publication-quality plot, white space is added because I've already adjusted it perfectly to the edges.
I want the fonts to be embedded, but everything else to stay the same!
Here is an example:
setEPS()
postscript(file = "~/Desktop/test.eps", family = "Helvetica", colormodel = "srgb", width = 5, height = 3)
plot(x = 1:10, y = 1:10, col = "red", main = "Keep everything the same but embed my fonts!")
dev.off()
embedFonts(file = "/Users/athena/Desktop/test.eps", format = "eps2write", outfile = "/Users/athena/Desktop/stupid.eps")
So far I have:
- installed ghostscript using homebrew: $ brew install ghostscript
- learned that embedFonts needs FULL paths, no tilda's allowed
- specified the format as "eps2write" because the default "ps2write" changes it to a postscript
I spent so much effort on "reproducible research" with open data, open code, open journal, bla bla bla... I really don't want to have to make my final figures using illustrator conversion or something :(
The reason this happens is because embedFonts internally calls Ghostscript which in turn tries to act smart by fitting an "optimal" bounding box by trimming out some of the surrounding white space.
We can prevent that by drawing an invisible box around the perimeter of our 5inx3in drawing area in R. Just add one more line to your code snippet:
setEPS()
postscript(file = "~/Desktop/test.eps", family = "Helvetica", colormodel = "srgb", width = 5, height = 3)
plot(x = 1:10, y = 1:10, col = "red", main = "Keep everything the same but embed my fonts!")
box(which="outer", col="white")
dev.off()
embedFonts(file = "/Users/athena/Desktop/test.eps", format = "eps2write", outfile = "/Users/athena/Desktop/stupid.eps")
Another way to go about this is Jonathan's answer here which basically uses sed to read in Bounding Box info from the input file and writes it to the output file: http://r.789695.n4.nabble.com/eps-file-with-embedded-font-td903387.html as pointed out by #neilfws in a comment above.

Weird lines appear in R graph after copying it "as metafile" to Word and exporting it as PDF

Journal in which I am submitting a research paper requires that article should be submitted in PDF-format. I am using R for statistics and graphs.
I have used basic formulas to print my graphs. barplot() for bar charts, boxplot() for boxplots and draw.triple.venn in VennDiagram package. I am not using special commands or formulas for device or graphical parameters.
I print my graphs in R and then copied them "as metafile" to produce high quality graphs.
When i attach these graphs in R they appear just fine. However, when I print my work as PDF in Word these lines appear to graphs.
Example for the first graph:
venn.plot <- draw.triple.venn(45, 34, 32,
14, 5, 11, 3, c(sprintf("Elevated\nWB Cr and Co"), sprintf("Mixed or\nsolid PT"), sprintf("Moderate to severe\ng.minimus atrophy")),
lwd = 4,
lty = 'solid',
cex = 3.5,
fontface = "bold",
fontfamily = "sans",
cat.cex = 1.8,
cat.fontface = "bold",
cat.default.pos = "outer",
cat.pos = c(-20, 20, 180),
cat.dist = c(0.115, 0.115, 0.095),
cat.fontfamily = "sans",
rotation = 1
);
Example for the second:
boxplot(df$Crmri~df$gmed2,log="y",yaxt="n",ylim=c(0.3,200));
axis(2,at=c(0,1,2,10,20,100),labels=c("0 ppb","1 ppb","2 ppb","10 ppb","20 ppb","100 ppb"),las=2);
I have several barplots in Word file and after saving as PDF these graphs are just fine.
At first I tried to save those graphs as metafile in R and adding them to Word after but the lines still appear. If I open my EMF-files in any other Viewer those lines are not there.
Any ideas? Thanks!
This has been discussed on r-help before. See:
https://stat.ethz.ch/pipermail/r-help/2011-September/289705.html
Seems to be due to the way Word converts documents to PDFs when you use "Save As" and then choose PDF.
If you have Acrobat (not just the reader), printing the document via the Adobe PDF "printer" should get rid of the lines. Otherwise, you may have to consider switching to another graphics format (e.g., png).
There's a new package export that just came out on CRAN that allows you to export graphs to Powerpoint or Word in native Office format. From there you can then save as PDF in Office without problems, without any weird lines appearing, see
https://cran.r-project.org/web/packages/export/index.html and
https://github.com/tomwenseleers/export
E.g.
install.packages("export")
library(export)
boxplot(count ~ spray, data = InsectSprays, las = 2)
graph2doc(file="plot.docx", width=7, height=5)
graph2ppt(file="plot.pptx", width=7, height=5)
Even after saving to PDF within Powerpoint this will give you a perfect quality vector format PDF without any weird lines :
Other advantage is that the Powerpoint version you get is fully editable vector format, enabling you to make any small required changes in the layout (it also fully supports transparency / alpha channels).
I can confirm that this issue still exists in Word for Office 365 and Word for Office 2016. Copying from R-Studio as a Metafile results in lines in the plots when you convert to PDF (using Word's Save as PDF function). Copying from R-Studio as a Bitmap or exporting as an image does not result in lines, but unfortunately the image quality in Word and PDF is not as clear as the Metafile. The response that described printing the document via the Adobe PDF Printer does avoid the lines, but I found that this approach loses the dynamic links in the text of the Word document (such as Table of Contents links). I have Adobe Acrobat Pro XI. So that solution does not work for me. In the end, the best solution I can find seems to be copying as a Bitmap. Unfortunately the image quality is not very good.

Smoothing line plot imperfections in R

Consider the following plot:
q1 <- c(1000000.0, 908364.8, 876009.1, 847892.8, 824808.3, 805416.2, 785266.2, 770997.1, 753908.6, 744599.9, 706777.6, 674659.9, 634654.4, 601440.4, 568259.7, 535361.3, 493679.9, 465526.5, 429766.6, 395244.7, 361483.2, 332136.6, 308574.5, 285500.6, 262166.2 ,237989.0 , 210766.1, 188578.1, 166762.3 , 140399.8 ,114865.5)
plot(q1, type = "l", lty = 1, lwd = 2, col = "darkolivegreen3", ylim = c(0,4*10^6))
As you can somewhat see on the graph, the line is not drawn perfectly, but has some "chainsaw" imperfections.. Is there a parameter or a line type that could fix this?
Thanks!
Anti-aliasing and other issues related to image rendering is controlled by the device you carry out the plotting on. On a windows system please refer to the ?windows help page for options and information. Unfortunately there doesn't seem to be any settings for anti-aliasing so then I guess it comes down to you graphics drivers. In other words, there is no quick fix.
However, you can try plotting to a file with png or jpeg instead. Even better is to plot to a vectorized file, such as pdf or svg where the concept of aliasing doesn't even apply (it is left to the device you view the file in, e.g. acrobat reader).

Resources