Search code examples
rr-markdownhtmlwidgetsfigcaptionvtree

Assign figure caption to html widget (vtree package) in R markdown output


I need to implement a figure caption in a plot that is generated by the vtree package in R markdown. I learned that this is a htmlwidget and figure captions should now be possible for htmlwidgets used in R markdown with install.packages('webshot') and webshot::install_phantomjs() (reference: https://bookdown.org/yihui/bookdown/html-widgets.html#ref-R-DT. But days after I am not really any step further. I did not find any example (show case) for this issue (fig.cap for htmlwidgets in R markdown in the net) so my hope is that someone out there can give me some help! In my iris dataset example, in Fig. 1 the caption is not working in contrast to Fig. 2.

my iris set example RMD file:

YAML

---
title: "test"
author: "TJ"
date: "14 12 2020"
output: html_document
---

code chunk 1: load libraries and data

knitr::opts_chunk$set(echo = TRUE)
library(vtree)
library(webshot)
library(tidyverse)
attach(iris)
df <- iris %>%
  select(Species) %>% 
  cbind(sapply(levels(.$Species), `==`, .$Species))

code chunk 2: Figure 1

{r fig1, echo=FALSE, fig.cap="Vtree plot"}
vtree(iris, "Species")

code chunk 3: Figure 2

{r fig2, echo=FALSE, fig.cap="Scatter plot iris dataset"}
plot(Sepal.Length, Sepal.Width, main="Scatterplot Example",
     xlab="Sepal Length ", ylab="Sepal Width ", pch=19) 

Solution

  • There is a workaround using the Magick package.You save the image as .png using grVizToPNG (make sure you comment this line out before you render your document or put it in a separate chunk with ´{r eval = FALSE}, otherwise you will get an error during rendering:

    ```{r eval=FALSE, echo = FALSE}
    
    myimage <- vtree(iris, "Species")
    saveMyimage <- grVizToPNG(myimage, width=800)
    ```
    

    Here you use the Magickpackage:

    ```{r magick, echo= FALSE}
    
    MyimagePNG <- image_read("myimage.png")
    image_annotate(MyimagePNG, "Vtree plot", size = 35, gravity = "southwest")
    
    ```
    

    enter image description here