Google Slides, R, d3: Insert Interactive Visualizations - r

I have created an interactive visualization using R and D3 and would like to insert it into a presentation while maintaining its interactivity. Is this possible?
Minimum working example (MWE:
library(networkD3)
# https://cdn.rawgit.com/christophergandrud/networkD3/master/JSONdata//flare.json
URL <- paste0(
"https://cdn.rawgit.com/christophergandrud/networkD3/",
"master/JSONdata//flare.json")
Flare <- jsonlite::fromJSON(URL, simplifyDataFrame = FALSE)
diagonalNetwork(List = Flare, fontSize = 10, opacity = 0.9)
Presently, I am trying to insert the visualization into a Google Slides presentation but I am open to other slide presentation solutions (e.g. LaTeX/Beamer, PowerPoint, etc.) as long as it achieves my goals. It is preferable to avoid having to mess around with JavaScript directly, hence why I am using the networkD3 package for R.
Aside: a problem with the Beamer route is that the themes are quite ugly and I have yet to see a pretty Beamer presentation.

Related

Create a carousel in Rmarkdown?

Is there any quick and easy way to create a simple carousel in an Rmarkdown doc?
What I know so far
I found slickr but run into errors setting options and knitting (the errors could be specific to me / mac - I am not sure at this point).
I believe it would be possible to hard code html/javascript into the RMarkdown doc i.e. the same way a carousel would be done in any other (regular) html document (i.e. using the html code here)- but I wonder if there's a native (R) way?
Example use
In my particular use case, I'm trying to display multiple complicated ggplots which are each sufficiently complex to make them require their own space (i.e. not faceted or grid.arrange as the size of each plot will get too small to read
Notes
Here is the slickr code I tried
library(texPreview)
library(slickR)
objpath <- file.path(getwd(),"slickr_files/figure-html")
if(!dir.exists(objpath)) { dir.create(objpath,recursive = TRUE) }
tex_opts$set(
fileDir = objpath, # path to save output
returnType = 'html', # return images ready for html
imgFormat = 'png' # return png images
)
knitr::kable(mtcars,'latex') %>%
texPreview::tex_preview(stem = 'kable-1')
# ! LaTeX Error: File `standalone.cls' not found.
A side note, if there's a better way of providing many (e.g. > 3) large, detailed plots that doesn't involve faceting, grid.arrange, or (my current preferred option) tabbing, please give a suggestion as a comment
The example works fine for me. Be sure to save your plots in the folder slickr_files/figure-html.
Then run:
```{r}
slickR::slickR(
list.files(objpath,full.names = TRUE,pattern = 'png'),
height = 200,
width = '95%')
```

Inserting an image or pdf into a word document in R

Im working with a loop that creates many tables etc. and exports it into word documents with ReporteRs package. So for example I then have a word document with many pages of different graphs, tables and text.
I want to insert an image (or pdf - either is fine) into it through the loop (since the loop produces many different word documents). I have downloaded the ImageMagick and magick packages to work with the images. Now I have my image in R, but I cant figure out how to add it to my document.
I know that ReporteRs has an addImage command that inserts external images (honestly im having trouble figuring that one out to). Is it possible adding internal images/pdf's to a document?
Hope you guys can gives me some tips. Thank you in advance!
I strongly recommand to migrate your code to officer as ReporteRs will be removed from CRAN on 2018-07-16. From the code #d125q wrote, this would be transformed as :
library(officer)
library(magick)
download.file("https://jeroen.github.io/images/frink.png", "frink.png")
dims1 <- attributes(png::readPNG("frink.png"))$dim/72
sample.image <- image_read("frink.png")
image_write(image_rotate(sample.image, 45), "frink_rotated.png")
dims2 <- attributes(png::readPNG("frink_rotated.png"))$dim/72
sample.doc <- read_docx()
sample.doc <- body_add_img(sample.doc, src = "frink.png", width = dims1[2], height = dims1[1] )
sample.doc <- body_add_img(sample.doc, src = "frink_rotated.png", width = dims2[2], height = dims2[1] )
print(sample.doc, target = "sample.docx")
You can plot images from magick to add them to a document using ReporteRs. Here's an example:
library(ReporteRs)
library(magick)
sample.doc <- docx(title="Sample")
## add original Frink
sample.image <- image_read("https://jeroen.github.io/images/frink.png")
sample.doc <- addPlot(sample.doc,
fun=plot,
x=sample.image)
## add rotated Frink
sample.doc <- addPlot(sample.doc,
fun=function(x) plot(image_rotate(x, 45)),
x=sample.image)
## save the document to disk
writeDoc(sample.doc, "sample.docx")
If anyone is wondering about this with the new officer. I needed to insert a pdf into my document. I converted the pdf to a picture. After migrating to officer, i ended up simply using this code from the officer package:
img.file <- file.path( R.home("doc201"), "P:/path to my picture", "name.png" )
doc201 <- body_add_img(x = doc201, src = "P:/path/name.png", height = 10, width = 6, pos = "after" )
The other answers worked too, but after i got used to officer this was the most simple way for me. Hope this is of help in the future! :)

R visuals not producing graphs in power bi

I am trying to create some R visuals in Power BI using the googleVis and/or plotly libraries, but no matter what I do, I can’t get Power BI to display anything. It always just says “No image was created. The R code didn’t result in creation of any visuals. Make sure your R script results in a plot to the R default device.” The issue occurs with plotly and googleVis libraries, so I think it may have something to do with the fact that they’re both browser-based outputs. Per Microsoft, plotly is supported in Power BI. I was hoping someone could tell me why I can’t get any of these example scripts to work in Power BI.
Example code which works in R, but not pbi.
plotly
library(plotly)
p <- plot_ly(midwest, x = ~percollege, color = ~state, type = "box")
p
googleVis
df=data.frame(country=c("US", "GB", "BR"),
val1=c(10,13,14),
val2=c(23,12,32))
Line <- gvisLineChart(df)
plot(Line)
Now, we can create RHTML custom visual in power BI
1) we can use Ploty - to use it you have load you "midwest" data in power BI table
2) then drag it to R script so it will available to R Script .
3) then run R script , it will work
You can render charts created by plotly as PNG:
p <- plot_ly(x = dataset$period, y = dataset$mean, name = "spline", line = list(shape = "spline"))
plotly_IMAGE(p, format = "png", out_file = "out.png")
But the problem with this is that, though rendered by plotly, the visualizations will not be interactive since it's just a PNG image.
If you want to create interactive visualizations using plotly. The only way you can do so far is to create a custom Power BI visualization and import it to your report. See this post for a good introduction.

What is a simple way to thumbnail some plots in R Markdown/knitr?

I am using R Markdown with knitr in R Studio to create and update a simple project website to keep my colleagues up to speed with a data analysis model I am building. There are some plots on the page, which (for smaller plots) so far has worked nicely, they can see the code and the results in the same place.
However, some plots have grown very large (and must remain large to allow quick side-by-side comparison of models), and don't fit on the page very well. I've used separately uploaded pdfs (with a link on the page) for some of them. It would be nicer if there was a simple way of generating thumbnails of some of these plots, so that the user can view a small plot image, click on it and then inspect the much larger image in detail. However, if it takes a lot of manual scripting for each plot instance, I'd rather not waste time on it and just upload the couple of pdfs. A similar question here talks about package, knitrbootsrap, but I don't want to thumbnail all my plots, just a select few. The package seems to use Magnific popup, but integrating it myself in a Markdown page seems like a hassle(?). I didn't find anything in the R Markdown reference guide. Of course a one way would be to generate two plots, one tiny, which is shown, and link it to another, larger plot image/pdf that is uploaded separately - but a simpler, more automatic way would be desireable.
Hence the question - is there a simpler way to generate clickable plot thumbnails in R Markdown?
So, this is what I came up with. Add a plot hook, so that you generate a full-resolution pdf image before generating a small image in the chunk:
allow_thumbnails <- function(x, options) {
if (!is.null(options$thumb)) {
filename <- sprintf("%s.full.pdf", strsplit(basename(x), "\\.")[[1]][1])
absolute_path <- file.path(dirname(x), filename)
# generate the full resolution pdf
pdf(absolute_path, width = options$thumb$width, height = options$thumb$height)
eval(parse(text = options$code))
dev.off()
# add an html link to the low resolution png
options$fig.link = absolute_path
}
knitr:::hook_plot_md_base(x, options)
}
And then in the Rmd file, I define the size of the full-resolution image using the thumb argument:
```{r init}
knit_hooks$set(plot = allow_thumbnails)
```
```{r my_large_plot, fig.width = 15, fig.height = 15, thumb = list(width = 45, height = 45)}
my_large_plot()
```
This generates an html file with a clickable png that takes you to the pdf.

Export the graph generated by rCharts in shiny application

I want to be able to export the charts generated in my shiny application using rCharts to Image and PDF formats. Is there any provision in the rCharts library for that?
I have earlier used ggvis, It gives an option for resizing the chart in the browser and also an option to download the chart in HTML or PNG format. Anything similar to that?
Edit 1:
I'm using nvd3 and polyCharts as my charting libraries currently.
To download as image or pdf you can use a$exporting(enabled = T), assuming your chart is called a.
library(rCharts)
a <- hPlot(Pulse ~ Height, data = MASS::survey, type = "scatter", group = "Exer")
a$exporting(enabled = T)
a
To follow up on my comment above, I was a bit too quick to respond, as the htmlwidget::saveWidget() function is meant for widgets developed under the htmlwidgets.org framework. However, rCharts has a similar function:
library(rCharts)
a <- nPlot(Pulse ~ Height, data = MASS::survey, type = "scatterChart", group = "Exer")
a$save("demo.html", standalone=TRUE)
Where 'demo.html' is standalone html file. Creating a png is as simple as taking a screenshot. Note that you can also call this function in a shiny app.

Resources