R eps export and import into Word 2010 - r

I'm having trouble with exporting eps files from R and importing into Word 2010.
I'm using ggplot2 plots, eg
library(ggplot2)
p <- qplot(disp,hp,data=mtcars) + stat_smooth()
p
Even after calling setEPS() neither of the following produce files which can be successfully imported.
ggsave("plot.eps")
postscript("plot.eps")
print(p)
dev.off()
The strange thing is that if I produce the plot using File -> Save As -> Postscript from the menu in the GUI, it can be imported correctly. However, when the Word document is subsequently exported as a pdf, the fonts in the graphic are a little jagged.
So my questions are:
What combination of (ggsave/postscript) settings allows me to produce eps files that can be imported into Word 2010?
How can I ensure the fonts remain clear when the Word document is exported as a pdf?
Update
After more investigation I have had more luck with cairo_ps to produce the plots. However, no text shows up when imported into Word.
Furthermore, after checking the various eps outputs (cairo_ps, save from the GUI, ggsave) in a latex document, it seems like the eps import filter in Word quite poor as the printed/pdf output doesn't match the quality of the latex'd document. The ggsave version (which uses postscript) did have some issues with colours that the other two methods didn't have though.
The conclusion is that this is a Word issue and therefore fortune(109) does not apply. I'd be happy to be proven otherwise, but I'll award the answer and the bounty to whoever can provide the commands that can replicate the output from the GUI in command form.

This worked for me... following advice in the postscript help page:
postscript("RPlot.eps", height = 4, width = 4, horizontal = FALSE, onefile = FALSE,
paper = "special")
library(ggplot2)
p <- qplot(disp,hp,data=mtcars) + stat_smooth()
p
#geom_smooth: method="auto" and size of largest group is <1000, so using loess. Use 'method = x' to #change the smoothing method.
#Warning message:
#In grid.Call.graphics(L_polygon, x$x, x$y, index) :
# semi-transparency is not supported on this device: reported only once per page
dev.off()
#quartz
# 2
The funny stuff at the end puts you on notice that this is only a Mac-tested solution, so far anyway.
Edit: I just tested it with R version 2.15.1 (2012-06-22) -- "Roasted Marshmallows": Platform: i386-pc-mingw32/i386 (32-bit) and MS Word 2007 in Win XP and it worked. Commands were Insert/Picture.../select eps format/select file.
Edit2: There is another method for saving besides directly using the postscript device. The savePlot method with an "eps" mode is available in Windows (but not in the Mac). I agree that the fonts are not as smooth as they appear on a Mac but I can discern no difference in quality between saving with savePlot and using save as from an interactive window.
savePlot(filename = "Rplot2", type = "eps", device = dev.cur(), restoreConsole = TRUE)
savePlot calls (.External(CsavePlot, device, filename, type, restoreConsole))

I solved the problem with exporting .eps files from R and importing into Word 2010 on Windows 7 using the colormodel="rgb" option (defaults to "srgb") of the postscript command.
postscript("RPlot.eps", height = 4, width = 4, horizontal = FALSE,
paper = "special", colormodel = "rgb")
library(ggplot2)
p <- qplot(disp,hp,data=mtcars) + stat_smooth(se=FALSE, method="loess")
p
dev.off()

You are probably better of using wmf as a format which you can create on Windows.

Word indeed doesn't support EPS very well.
A better solution is to export your graphs to Word or Powerpoint directly in native Office format. I just made a new package, export, that does exactly that, see
https://cran.r-project.org/web/packages/export/index.html and
for demo
https://github.com/tomwenseleers/export
Typical syntax is very easy, e.g.:
install.packages("export")
library(export)
library(ggplot2)
qplot(Sepal.Length, Petal.Length, data = iris, color = Species,
size = Petal.Width, alpha = I(0.7))
graph2doc(file="ggplot2_plot.docx", width=6, height=5)
graph2ppt(file="ggplot2_plot.pptx", width=6, height=5)
Output is vector format and so fully editable after you ungroup your graph in Word or Powerpoint. You can also use it to export statistical output of various R stats objects.

You can use R studio to knit html files with all of your plots and then open HTML files with Word.
knitr tutorial

Related

Embedded pdf-font in R-plot is not recognized by InDesign although available

Using ggplot2, extrafont and R's pdf device I have built plots in the cmyk colormodel that incorporate certain non-Windows fonts. The pdf-output looks fine and shows that the font has been embedded correctly, for instance "Arial-BoldMT".
Unfortunately, when trying to import the pdf into Adobe InDesign, I get the error message that the font "Arial-BoldMT" is not currently available, which also happens to the non-Windows fonts I mentioned above.
I suppose there might be a problem with the name of the embedded font that cannot be recognized by InDesign, since the font is very well available as "Arial" including all the variations such as "bold".
Any suggestions how to get those fonts working in InDesign by either adjusting the R script or using InDesign?
Thank you!
Here is a sample plot, similar to the plots I need to produce, just leaving out the unnecessary code lines:
library(ggplot2)
library(extrafont)
# define font
font <- "Arial"
# sample data
x <- data.frame(c("Personnel Costs", "Non-Personnel Costs", "Investments"),
c(33, 22, 45))
colnames(x) <- c("costs", "percent")
# plot
plot <- ggplot(x, aes("", y = percent, fill = factor(costs), width = 1.2))+
geom_bar(width = 4, stat="identity")+
# add the text (no font specification here)
geom_text(aes(label=costs),fontface = "bold")+
# no legend
theme(legend.position = "none") +
# pie-chart
coord_polar("y", start = 0.42, direction = 1)
# save plot
pdf("plot.pdf", family=font, colormodel="cmyk")
plot
dev.off()
PS: Using ggsave and embedFonts() with Ghostscript produced the same results.
Note: Using "Calibri" with the pdf device or ggsave and embed_fonts() does not work at all.
It seems if the font was not properly embedded into the pdf.
By running embed_fonts() after saving the plot, the according font got embedded and now works in InDesign.
I just needed:
library(extrafont)
embed_fonts(file="plot.pdf", outfile="plot.pdf")

Plotting device with RStudio

I have issue with plotting lines over my existing plot in .Rmd in RStudio. I ran the code within the code chunk in .Rmd (⌘ + return) and the plot gives me a graph within the .Rmd (new feature of RStudio v1.0), however when I ran the second code lines, an error shows up.
plot(density(with$glucose),
ylim = c(0.00, 0.02),
xlab = "Glucose Level",
main = "Figure",
lwd = 2)
lines(density(without$glucose),
col = "red",
lwd = 2)
Error in plot.xy(xy.coords(x, y), type = type, ...) : plot.new has not been called yet
On the other hand, if I copy and paste the codes into the console, I could get the plot I want, in the plot viewer within RStudio.
In addition, when I ran some other codes within the .Rmd (⌘ + return), my plots in the plot viewer in RStudio disappear. This means I have to do copy-paste into the console instead of using the (⌘ + return) shortcut.
Does anyone have the same problem?
This is a known problem, but you can solve it very easy: Press Ctrl+Shift+Enter to run the complete chunk, then everything works fine and you don't have to copy-and-paste all thing to the console.
So do all your plots in one chunk and run this chunk. This will produce you the plot within the RMD file (as you mentioned: new feature of RStudio 1.0)
If you're not a fan of the inline output / notebook mode for R Markdown documents, you can also disable it within the Global Options dialog -- try disabling the option:
Show output inline for all R Markdown document

How to convert text within EPS figures to vector outlines in R?

I am preparing a paper for submission to a journal which requires vector graphics to be submitted in EPS format, with all text within figures converted to outlines. Converting text to vector outlines helps avoid font problems in the final layout. The journal requirements are available here.
EPS figures can easily be created in R using ggplot2:
library(ggplot2)
ggsave(filename = "file.eps")
or using setEPS() and the postscript device, as explained previously here:
setEPS()
postscript("filename.eps")
plot(1:10)
dev.off()
My question is: how can you convert text within the figures into vector outlines? I have found information on how to do this in other software (e.g. Illustrator or InDesign), but I would like to know if there is a way to do it directly in R.
Install ghostscript using your distro's package manager if you're under linux or download it for windows (there's also a portable version), for mac you can probably use brew. Then invoke gs or gs.exe from within R like in this SO question.
library(ggplot2)
data(diamonds)
gs.cmd <- "gs" # ghostscript executable
# gs.cmd <- "C:/path/to/gs.exe" # Windows
p <- qplot(x=carat, y=price, color=clarity, data=diamonds)
ggsave(p, filename="test.eps")
system(paste(gs.cmd,"-o test_outline.eps -dNoOutputFonts -sDEVICE=eps2write test.eps"))

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.

Export image from R to word with alpha channel (transparency)

I am wanting to export an R produced figure to Word. The figure contains transparency (alpha channel). Below is some example code - when exported to Windows metafile it throws an error:
Warning message:
In plot.xy(xy, type, ...) :
semi-transparency is not supported on this device: reported only once per page
Exporting to SVG produces the desired result, but this image format is not supported by MS Office. Is there a way around this? What image type could I use while retaining the alpha channel? PNG is possible, but this doesn't produce very crisp graphics - it loses the clear vectorized image.
# Get some colours with transparency (alpha = 0.6)
col.dot <- rainbow(5, alpha = .6)
# Save to svg file - OK
svg("test_fig.svg")
plot(1:5,col = col.dot, pch=15)
dev.off()
# Save to wmf - warning "semi-transparency is not supported on this device..."
win.metafile("test_fig.wmf")
plot(1:5,col = col.dot, pch=15)
dev.off()
I should add, this is on a Windows system (Windows 8 64 bit, with Word 2013)
I just made a new package export to easily export R graphs to Office (Word, Powerpoint), see
https://cran.r-project.org/web/packages/export/index.html and
for demo https://github.com/tomwenseleers/export.
Typical syntax is very easy, e.g.:
install.packages("export")
library(export)
library(ggplot2)
qplot(Sepal.Length, Petal.Length, data = iris, color = Species,
size = Petal.Width, alpha = I(0.7))
graph2ppt(file="ggplot2_plot.pptx", width=6, height=5)
Output is vector format and so fully editable after you ungroup your graph in Powerpoint. You can also use it to export to Word, Excel, Latex or HTML and you can also use it to export statistical output of various R stats objects.
This results in a fully editable, high quality Powerpoint graph in native Office vector-based DrawingML format, which you can also readily copy & paste as enhanced metafile if you like, and which unlike the EMFs exported from R also fully supports transparency.
From the help of win.metafile:
There is support for semi-transparent colours of lines, fills and text
on the screen devices. These work for saving (from the ‘File’ menu) to
PDF, PNG, BMP, JPEG and TIFF, but will be ignored if saving to
Metafile and PostScript.
So you cannot use transparency in a metafile. You can try saving as png and increasing the resolution of the output.

Resources