How to increase resolution of ggplots when exporting using officer R - r

I want to export charts to a PPT and am using the officer package to achieve the same. However, the default resolution of the charts is low and I would like to change that. I am currently using the following call
ph_with_gg(p1,type = "chart",res = 1200)
where p1 is a ggplot object. On running this, I get the following error:
Error in png(filename = file, width = width, height = height, units =
"in", :
formal argument "res" matched by multiple actual arguments
Would really appreciate the help around this

Rather than using png, for high-resolution plots in PPT you should be using vector graphics.
See under extensions:
Vector graphics with package rvg
The package rvg brings an API to
produce nice vector graphics that can be embedded in PowerPoint
documents or Excel workbooks with officer.
This package provides functions dml() and ph_with() corresponding method to export ggplots to .pptx as vector graphics.
Example:
library(ggplot2)
library(officer)
library(rvg)
library(magrittr)
data(iris)
read_pptx() %>%
add_slide(layout='Title and Content',master='Office Theme') %>%
ph_with('Iris Sepal Dimensions', location = ph_location_type(type="title")) %>%
ph_with(dml( ggobj=
ggplot(iris, aes(x=Sepal.Length,y=Sepal.Width,col=Species)) +
geom_point()), location = ph_location_type(type="body")) %>%
print('iris_presentation.pptx')
As an additional benefit, you will be able to edit the charts in PowerPoint. For example, if you decided to capitalize the names of the 3 species, you could just edit the chart instead of editing the data and regenerating the slides. (You can also make the plots non-editable, but editable is the default.)

Is it important that the plot is saved to a presentation in the code?
Otherwise using:
ggsave(filename = file, p1, width = width, height = height, dpi = dpi)
will give you a png of any resolution you need..
(provided that filename ends with .png and you set width, height and dpi to appropriate values)

Related

Is it possible to reduce the size of a markdown html-report by including only specific parts of a package?

Is there a way to reduce the filesize of a R Markdown html-report by including only needed functions (e.g. plotly scatterplot) in the result file. My Report is self contained.
By creating a new R Markdown the resulting file size is ~735 KB. By adding a new chunk with a simple plotly plot the file size increases to ~4.834 KB.
```{r additional plotly example}
plotly::plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
```
Plotly gives you the possibility to leverage threw different bundles.
This is done by partial_bundle().
The different sizes of the bundles can be found here:
https://github.com/plotly/plotly.js/blob/master/dist/README.md#partial-bundles
For further information:
https://plotly-r.com/performance.html
https://www.rdocumentation.org/packages/plotly/versions/4.9.0/topics/partial_bundle

Reading PDF plots, arranging them on a grid, save in one-page PDF using R

I have 3 R plots saved as pdf files (upper_left.pdf, upper_right.pdf, lower.pdf) as vector graphic and want to make a one-page pdf file and arrange them on it as follows:
What I have tried already
I have tried reading the pdf's using magick::image_read_pdf and appending them using magick::image_append. More specifically,
library(magick)
panel.ul <- image_read_pdf("upper_left.pdf")
panel.ur <- image_read_pdf("upper_right.pdf")
panel.l <- image_read_pdf("lower.pdf")
whole <- c(panel.ul, panel.ur) %>%
image_append() %>%
c(panel.l) %>%
image_append(stack = TRUE)
The first issue is magick::image_read_pdf imports the plot as png (if I'm right, not vector graphic though).
magick::image_append also 'works' and gives me what I want in viewer pane (in RStudio, next to Help).
I then try to save them using export::graph2pdf(whole), but it gives me a blank page.
So, if I am to use magick, there are two issues that need to be solved:
importing plots as vector graphic objects (do not know the technical term in R)
Exporting the stacked plot to a vector pdf file.
How can I solve it? thanks in advance.
You're basically done. You only need to add
plot(whole) # plot the external object generated in ImageMagick to R's plotting device
savePlot(type = "pdf") # saves the current plotting device to a pdf file.
You will find your plot in your workoing directory called "Rplot.pdf".
savePlot has many options to customize your pdf output. Make sure to check ?savePlot.
To recreate your scheme from above youll need to temporarily save the upper panel as a separate pdf before you paste it to on top of the lower panel:
whole2 <- image_append(c(panel.ul, panel.ur))
plot(whole2)
savePlot("whole2.pdf", type = "pdf")
If the upper and lower panel do not look proportionate you can use the heght and width parameters of savePlot to adjust the size of the first pdf.
panel.upr <- image_read_pdf("whole2.pdf")
final <- image_append(c(image_append(panel.upr),panel.l), stack = TRUE)
plot(final)
savePlot("final.pdf", type = "pdf")

Specific fonts in ggplot2 not saving to pdf error

I'm trying to save multiple plots to one pdf, typically I use:
# creating pdf from four panels
# these aren't reproducible but any ggplot will recreate error essentially
pdf(file = "Fig.1", height = 14, width = 14)
Fig.1<- grid.arrange(p1,p2,p3,p4)
print(Fig.1)
dev.off()
However, I want to use a specific font in the plots.
I have thus downloaded and installed the fontextrapackage, intalled and loaded the fonts with loadfonts(device = "win"). I then use theme(text=element_text(family="Calibri")) within the ggplot call.
When I re-run code individual plots will look fine in R itself. I can also successfully use grid.arrange using gridExtra to arrange them and check them within R itself. However, when I use:
pdf(file = "Fig.4.trw.pdf", height = 14, width = 14)
Fig.4.trw<- grid.arrange(p1,p2,p3,p4)
I get a bunch of errors associated to fonts:
In grid.Call(C_textBounds, as.graphicsAnnot(x$label), ... :
font width unknown for character 0x30
I've also tried to use ggsave but that isn't working either, please help!
Thanks

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.

R eps export and import into Word 2010

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

Resources