Search code examples
rplotr-lavaandiagrammer

Save DiagrammeR object to PNG on disc


I am using the lavaanPlot-Package to plot my Path Model created with lavaan. Works like a charm. Just to make it easier here is a reproducible example

Reproducible Example

library(pacman)
p_unload()
p_load(dplyr,lavaan,webshot,lavaanPlot)
model <- 'mpg ~ cyl + disp + hp
          qsec ~ disp + hp + wt'

fit <- sem(model, data = mtcars)
summary(fit)

plot <- lavaanPlot(model = fit, 
                   node_options = list(shape = "box", fontname = "Helvetica"), 
                   edge_options = list(color = "grey"), 
                   coefs = F)

plot

However I would like to save the result to a png file on my disc (rather than utilizing some form of screenshot). Digging in the docs I found out that lavaanPlot returns a Diagrammer Object. I tried to get a png file with three different approaches

Approaches

1. Webshot
Gives me the error webshot.js returned failure value: 1
2. export_graph
I found some suggestion how to fix it this link on SO, suggesting to use DiagrammeR export_graph. However this gives me the following error:

Fehler: `export_graph()` REASON:
* The graph object is not valid 

3. export_svg
Additionally I found this suggested solution on github, which I couldnt get to work either. It produces a SVG file for me which I cant open properly

# Try 1 using webshot
webshot("Plot_test_webshot.png")

# Try 2 export_graph
plot %>%
  export_graph(file_name = "pic.png",
               file_type = "png")

export_graph(plot,
             file_name = "pic.png",
             file_type = "png")

# Try 3 export_svg
plot %>%
  export_svg() %>%
  charToRaw %>% 
  rsvg_pdf("./path_to_svg_file.svg")

Solution

  • I was able to find a solution in the Github of the maintainer of the package.
    Posting this in the hope that anyone in the future looking for a solution will find this

    # Export Function for lavaanPlot Obtained from github
    # https://github.com/alishinski/lavaanPlot/blob/export_plots/R/plotExportFunctions.R
    
    save_png <- function(plot, path){
      DiagrammeRsvg::export_svg(plot) %>%
        charToRaw() %>%
        rsvg::rsvg() %>%
        png::writePNG(path)
    }
    

    Also on Github there is a branch in which this functionality is already included.