Does officer-package accept ggsurvplot-object? - r

I'm trying to export a ggsurvplot-object to powerpoint with officer-package with no success. I was able to find a lot of instructions on how to use now obsolute ReporterS-package for this and a few mentions that officer should work as well. There seems to be nothing in the documentation mentioning this. So should this work at all? Is it possible to get a vectorized survival plot to a pptx-slide with these tools?
totsur <- ggsurvplot(yhd1,
data = sappivertailu,
combine=TRUE,
xlab = "Time, months",
ylab="Survival",
title="Overall survival",
lwd=2,
palette="jco",
xscale = "d_m",
xlim = c(0,730.5),
break.x.by = 91.3,
risk.table = TRUE,
pval = TRUE,
fontsize = 3)
totsur
my_vec_graph <- dml(code = totsur)
doc <- read_pptx()
doc <- add_slide(doc, layout = "Overall survival", master = "Office Theme")
doc <- ph_with(doc, my_vec_graph, location = ph_location_fullsize() )
print(doc, target = "Sappitutkimus/Charts/survi1.pptx")
Changing the dml(ggobj = totsur) neither works. What am I doing wrong?
Edit: Thanks for all the comments below! And another update. There was nothing wrong with the data. After a little debugging, my original data produces the intended result.
One problem remains. Package does not seem to able to add risk table and survival curve in the same slide. Yes, you can pass this by making two separate plots on separate slides but I don't think that's good practice.
If I'm not totally mistaken, officer and ReporteRs have some code in common and this issue was present there as well. https://github.com/kassambara/survminer/issues/314
Does anyone know a way around this? Here's a bit more compact chunk I'm currently using. This works fine otherwise.
yhd1 <- survfit(Surv(sappivertailu$Survi, sappivertailu$Kuolema) ~ Arm, data=koe)
totsur <-
ggsurvplot(yhd1,
combine = TRUE,
data = sappivertailu,
# risk.table = TRUE,
pval = TRUE,
fontsize = 3
)
totsur
my_vec_graph <- rvg::dml(ggobj = last_plot())
doc <- read_pptx()
doc <- add_slide(doc, layout = "Title and Content", master = "Office Theme")
doc <- ph_with(doc, my_vec_graph, location = ph_location_fullsize() )
print(doc, target = "Sappitutkimus/Charts/survi1.pptx")
Edit n:o 2: And a tip about the desired result.

Sure could you export ggsurvplots. to pptx via officer. There are two issues with your code. First you have to make use of rvg::dml(ggobj = ...) . Second you set layout = "Overall survival". But there is no layout with this name in the default pptx shipped with officer, i.e. you could only use layouts which are present in the pptx template. Fixing both issues and making use of the basic example from the docs of ggsurvplot:
require("survival")
#> Loading required package: survival
library(survminer)
#> Loading required package: ggplot2
#> Loading required package: ggpubr
library(officer)
fit<- survfit(Surv(time, status) ~ sex, data = lung)
# Basic survival curves
ggsurvplot(fit, data = lung)
my_vec_graph <- rvg::dml(ggobj = last_plot())
doc <- read_pptx()
doc <- add_slide(doc, layout = "Title and Content", master = "Office Theme")
doc <- ph_with(doc, my_vec_graph, location = ph_location_fullsize() )
print(doc, target = "survi2.pptx")
EDIT If you want to have multiple contents on the same slide you could change the layout to Two Content and make use of ph_location_left/right:
doc <- read_pptx()
doc <- add_slide(doc, layout = "Two Content", master = "Office Theme")
doc <- ph_with(doc, my_vec_graph, location = ph_location_left() )
doc <- ph_with(doc, my_vec_graph, location = ph_location_right() )
print(doc, target = "survi2.pptx")

Somewhat to my amazement, you can use the code = argument within dml() if you embed your suvival plot in a print() statement. Be sure to include newpage = FALSE:
require("survival")
# Loading required package: survival
library(survminer)
#> Loading required package: ggplot2
#> Loading required package: ggpubr
library(officer)
fit<- survfit(Surv(time, status) ~ sex, data = lung)
# Basic survival curves
p = ggsurvplot(fit, data = lung, risk.table = TRUE)
my_vec_graph <- rvg::dml(code = print(p, newpage = FALSE))
doc <- read_pptx()
doc <- add_slide(doc, layout = "Title and Content", master = "Office Theme")
doc <- ph_with(doc, my_vec_graph, location = ph_location_fullsize() )
print(doc, target = "survi2.pptx")

Related

Exporting a multigraph from ggplot to powerpoint with officer

somehow I am not able to properly export a plot containing three subplots into my PowerPoint with the officer package. I will most an MWE with the same but different data that produces the plot that I want to export
library(fpp3)
library(officer)
library(rvg)
p1 <- global_economy %>%
filter(Code == "CAF") %>%
gg_tsdisplay(difference(Exports), plot_type='partial')
#PPT
p_dml <- rvg::dml(ggobj = p1, editable = F)
my_pres <- read_pptx("...path/presentation.pptx")
my_pres <- add_slide(my_pres,layout = "Headline 1-zeilig", master = "Master-Design") #should be adjusted
my_pres<- ph_with(my_pres, value = p_dml , location = ph_location_fullsize())
print(my_pres, target = "...path/presentation.pptx")
This is the graph that I am producing inside R:
But in the final PowerPoint only the lower right figure is displayed and not all three graphs.
The issue is that the object returned by gg_tsdisplay is not a ggplot object but a list of ggplot objects instead. As a consequence only the last element of this list is exported to the pptx or you get an error in the case where your first convert to a dml object.
One possible fix would be to build your multi plot using the patchwork package which as a side effect will "convert" the list of plots to a ggplot object. After doing so you could easily export to pptx whether as a ggplot object or as an dml object. In my code below I use patchwork::wrap_plots and use the design argument to mimic the layout of your multi plot:
library(fpp3)
library(officer)
library(rvg)
p1 <- global_economy %>%
filter(Code == "CAF") %>%
gg_tsdisplay(difference(Exports), plot_type='partial')
library(patchwork)
p1 <- p1 |>
wrap_plots(design = "AA\nBC")
p_dml <- rvg::dml(ggobj = p1, editable = F)
my_pres <- read_pptx()
my_pres <- add_slide(my_pres,layout = "Title and Content", master = "Office Theme")
my_pres<- ph_with(my_pres, value = p_dml, location = ph_location_fullsize())
print(my_pres, target = "presentation.pptx")

Image not displayed in row of flextable on export ppt

i am trying to export to powerpoint a flextable that has rows with pictures on it, but not displaying on the generated powerpoint.
However it works well on the R studio Viewer.
Do you have any idea where the problem is coming from plz?
Thanks in advance
library(kableExtra)
library(flextable)
library(officer)
doc <- read_pptx()
img.file <- file.path( R.home("doc"), "html", "logo.jpg" )
myft <- flextable( head(mtcars),
col_keys = c("am", "separator", "gear", "mpg", "drat", "qsec" ))
myft <- compose( myft, i = ~ qsec > 18, j = "qsec",
value = as_paragraph(as_image( src = img.file, width = .20, height = .15))
)
myft <- autofit(myft)
myft
doc <- add_slide(doc)
doc <- ph_with(doc, value = myft, location = ph_location_template(top = 2, width = 4, type = "body"))
print(doc, target = "./cars.pptx")
system2('cmd', args = c('/c', '"./cars.pptx"'))
This is not possible with PowerPoint, you can read documentation here: https://davidgohel.github.io/flextable/articles/display.html#limitation-for-powerpoint-1
Using images in flextable is not supported when output format is PowerPoint. This is not a choice nor an unimplemented feature. This is because PowerPoint is not able to embed images in a table cell. That’s a PowerPoint limitation.

Mutliple formatted text on pptx by using officer package on R

Ciao,
I'm writing a code to generate an automatic report using officer package. I was wondering how and if I can write some text with different font. In my case I'd like to write some normal text and some bold words.
Let me show you what I get. I use these functions to generate fp_text objects:
fp_normal <- function(){
return( fp_text(color = "black", font.size = 16,
bold = FALSE, italic = FALSE,
underlined = FALSE, font.family = "Arial",
shading.color = "transparent") )
}
fp_bold <- function(){
return( fp_text(color = "black", font.size = 16,
bold = TRUE, italic = FALSE,
underlined = FALSE, font.family = "Arial",
shading.color = "transparent") )
}
I used to use combination of pot function by using sum operator and function textProperties:
pot("not bold ") + pot("and bold", textProperties(font.weight = "bold") )
My question is: how should I combine fp_normal and fp_bold functions with ph_with_text function?
I have updated the package to make that kind of operation easier. Usage of id_chr is not easy and the code below give the advantage to not use it :)
library(magrittr)
library(officer)
fp_normal <- fp_text(font.size = 24)
fp_bold <- update(fp_normal, bold = TRUE)
fp_red <- update(fp_normal, color = "red")
pars <- block_list(
fpar(ftext("not bold ", fp_normal), ftext("and bold", fp_bold)),
fpar(ftext("red text", fp_red))
)
my_pres <- read_pptx() %>%
add_slide(layout = "Title and Content", master = "Office Theme") %>%
ph_with(pars, location = ph_location_type(type = "body") )
print(my_pres, target = "test.pptx")
Ok, at the end I think I've got it.
To apply different styles is in enough to combine ph_with_text function with ph_add_text function.
Namely ph_add_text do the same sum operator do for pot function. Keep in mind that, in order to refer to a certain line you have to provide id_chr argument. You can deduce the correct value by using slide_summary(ppt) command just after you run ph_with_text.
ppt <- read_pptx()
ppt <- add_slide(ppt, "Title and Content", master = "Office Theme")
ppt <- ph_with_text(ppt, "Some NOT bold text ", type = "body", index = 1)
slide_summary(ppt) # I see that the id is 2. Now I can delete this line.
ppt <- ph_add_text(ppt, "and some bold text", type = "body", style = fp_bold(), id_chr = 2)
print(ppt, target = "boldTest.pptx")
For the fp_bold() function see above in the question.
Ad this point we can add other pieces of text with different formats by keeping using ph_add_text (and maybe "\n" if we want write in new lines.
Ciao

Interactive R Markdown Document with ggmap

I'm working with the ggmap tutorial by Manuel Amunategui over at http://amunategui.github.io/ggmap-example/. It is a wonderful introduction to the ggmap package and thankfully I understand his tutorial.
However, I am also trying to make this material interactive through R markdown. When I run the below document, for some reason the rendering of the map is of very low quality. In my standard .R script the image produced is way better. Any thoughts as to what might cause the drastic difference in quality?
Also, in R Markdown, is it possible to have custom sizing of the images as well as placement? I am specifically interested in making the map larger and/or displaying another map with it side-by-side.
This first block of code is just to get your hands on the data if desired.
#install.packages("RCurl"); install.packages("xlsx"); install.packages("zipcode"); install.packages("ggmap")
library(RCurl)
library(xlsx)
# NOTE if you can't download the file automatically, download it manually at:
#'http://www.psc.isr.umich.edu/dis/census/Features/tract2zip/'
urlfile <-'http://www.psc.isr.umich.edu/dis/census/Features/tract2zip/MedianZIP-3.xlsx'
destfile <- "census20062010.xlsx"
download.file(urlfile, destfile, mode="wb")
census <- read.xlsx2(destfile, sheetName = "Median")
#census <- read.xlsx2(file = "census20062010.xlsx", sheetName = "Median")
head(census)
# clean up data
# census <- census[c('Zip','Median..', 'Pop')]
names(census) <- c('Zip','Median', 'Pop')
census$Median <- as.character(census$Median)
census$Median <- as.numeric(gsub(',','',census$Median))
census$Pop <- as.numeric(gsub(',','',census$Pop))
head(census)
# get geographical coordinates from zipcode
library(zipcode)
data(zipcode)
census$Zip <- clean.zipcodes(census$Zip)
census <- merge(census, zipcode, by.x='Zip', by.y='zip')
census$location <- paste0(census$city, ", ", census$state)
names(census) <- sapply(names(census), tolower)
# saved census to census.rdata at this point...
The next chunk of code below is what is in the markdown file.
```{r, message=FALSE, echo=FALSE}
library(ggmap)
library(ggplot2)
load("census.rdata")
inputPanel(
textInput("loc", label = "Location", value = "Orlando, FL"),
sliderInput("zoom", label = "Zoom Level",
min = 1, max = 12, value = 10, step = 1)
)
renderPlot({
census2 <- census[census$location == input$loc,]
map <- get_map(location = input$loc,
zoom = input$zoom,
maptype = 'roadmap',
source = 'google',
color = 'color',
filename = "ggmapTemp")
print(ggmap(map) +
geom_point(
aes(x=longitude, y=latitude,
show_guide = TRUE, size=Median),
data=census2, colour = I('red'), na.rm = T)
)
})
```
Thanks for your help!

embed rChart in Markdown

I am trying to embed a NVD3 chart in a Markdown document. I am on a Ubuntu64 system with RStudio 0.98.932, R 3.1.0, rCharts 0.4.2, the browser is Chrome.
The instructions/code from this link:
```{r}
library(rCharts)
library(knitr)
opts_chunk$set(comment = NA, results = "asis", comment = NA, tidy = F)
hair_eye_male = subset(as.data.frame(HairEyeColor), Sex == "Male")
n1 <- nPlot(Freq ~ Hair, group = 'Eye',
data = hair_eye_male, type = 'multiBarChart'
)
n1$set(width = 600)
# n1$show('iframesrc', cdn = TRUE) # option 1
# n1$show('inline', include_assets = TRUE, cdn = TRUE) # option 2
```
Neither of the options [n1$show] work, I just get code in a browser. Is there another way of including NVD3 documents in Markdown?
To get rCharts to work with knit2html, you will need to use the print method with the argument include_assets = TRUE. This is because knitr will not add the js and css assets required by an rCharts plot automatically. Here is a minimal working example.
## MorrisJS with Knit2HTML
```{r results = 'asis', comment = NA}
require(rCharts)
data(economics, package = 'ggplot2')
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line',
data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$print('chart2', include_assets = TRUE)
```
Note that you need to use m1$print('chart2', include_assets = TRUE, cdn = TRUE) if you intend to publish your chart on RPubs, for otherwise the JS and CSS assets will be served from your local library.
Source:Knitr HTML in R Markdown
This code is working for me. I am using ubuntu64 and same config you mentioned.
```{r, echo=FALSE,results='asis',comment=NA}
library(rCharts)
hair_eye_male <- subset(as.data.frame(HairEyeColor), Sex == "Male")
n1 <- nPlot(Freq ~ Hair, group = "Eye", data = hair_eye_male, type = "multiBarChart")
n1$show('iframesrc',cdn=TRUE)
```
Note : you must write results='asis' and comment = NA in chunk options and not use opts_chunk$set as you have in your code block and what you pasted to copy.com.

Resources