Borexino
Borexino

Reputation: 842

Save interactive Plotly in PDF or EPS in R

library(tidyverse)
library(easyalluvial) # https://github.com/erblast/easyalluvial
library(parcats)      # https://github.com/erblast/parcats

# My data
knitr::kable(head(mtcars2))

# My Alluvial
MyAlluvial <- alluvial_wide(data = mtcars2, 
                            max_variables = 5, 
                            fill_by = 'first_variable')

# My Nice alluvial
p <- parcats(MyAlluvial, marginal_histograms = FALSE, data = mtcars2)
p

# Saving PDF
pdf("/Users/Master/Downloads/MyAlluvial.pdf")
p
dev.off()

I'm able to save the plot as png/jpg using RStudio GUI, but I cannot save it in a vector format (neither pdf nor eps). As far as I known, interactive plot was generated using Plotly. I can save printing a PDF from the browser but I don't like this!!

Upvotes: 1

Views: 818

Answers (1)

Emmanuel Hamel
Emmanuel Hamel

Reputation: 2213

I was able to save your graph in a PDF file with the following code :

library(rmarkdown)
library(pagedown)

vector_RMD_Content <- c(
'---',
'title: "Untitled"',
'output: html_document',
'---',
'```{r setup, include=FALSE}',
'knitr::opts_chunk$set(echo = TRUE)',
'```',
'```{r cars}',
'library(tidyverse)',
'library(easyalluvial)', 
'library(parcats)',
"MyAlluvial <- alluvial_wide(data = mtcars2, max_variables = 5,  fill_by = 'first_variable')",
'p <- parcats(MyAlluvial, marginal_histograms = FALSE, data = mtcars2)',
'p',
'```')

zzfil <- tempfile(fileext = ".Rmd")
writeLines(text = vector_RMD_Content, con = zzfil)

render(input = zzfil,
       output_file = "C:/stackoverflow.html")

chrome_print("C:/stackoverflow.html", 
             output = "C:/testpdf2.pdf")

A html file with your graph is generated with Rmarkdown. After, the HTML file is printed to PDF with the R function chrome_print of the R package pagedown.

Upvotes: 2

Related Questions