htmlrggplot2htmltools

Insert image (file or R object) into existing html file from R script


I include two ggplotly() graphics in a html file, eg.

library(ggplot2)
library(plotly)
library(htmltools)

g1 <- ggplot(data=data.frame(x=1:10, y=1:10)) +
  geom_point(aes(x=x, y=y))
g2 <- ggplot(data=data.frame(x=11:20, y=1:10)) +
  geom_point(aes(x=x, y=y))
l1 <- ggplotly(g1)
l2 <- ggplotly(g2)

htmltools::save_html(htmltools::tagList(l1,l2), file ="index.html")

And now want to include an image in the same html file,eg a ggplot2 object:

foto <- imresize(load.image(system.file("ex/logo.tif", package="terra")),0.25)
fotodf <- as.data.frame(foto,wide="c") %>% mutate(rgb.val=rgb(c.1,c.2,c.3))
p <- ggplot(fotodf,aes(x,y))+geom_raster(aes(fill=rgb.val)) + scale_fill_identity() +
  scale_y_reverse() + coord_fixed() + theme_void()

or insert the image file into the html file directly. The problem is that I do not find how to insert either the p ggplot object or the logo.tif file into index.html


Solution

  • We could do something like this:

    library(ggplot2)
    library(plotly)
    library(htmltools)
    
    g1 <- ggplot(data=data.frame(x=1:10, y=1:10)) +
      geom_point(aes(x=x, y=y))
    g2 <- ggplot(data=data.frame(x=11:20, y=1:10)) +
      geom_point(aes(x=x, y=y))
    l1 <- ggplotly(g1)
    l2 <- ggplotly(g2)
    
    # the ggplot graphs
    html_file <- htmltools::tagList(l1, l2)
    
    image_path <- "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/R_logo.svg/1920px-R_logo.svg.png"
    # or any image in the www folder
    html_image <- tags$img(
      src = image_path, 
      alt = "image", 
      width = "100px", 
      height = "100px", 
      style = "position: absolute; top: 100px; left: 100px;"
    )
    # ggplot graphs with 
    html_file_with_image <- htmltools::tagList(html_file, html_image)
    htmltools::save_html(html_file_with_image, file = "index.html")
    
    

    enter image description here