9

I would like to show ggplot objects on the browser as a svg using rmarkdown.

---
title: ""
output: html_document
---

```{r setup, include = FALSE}
library(svglite)
library(ggplot2)
knitr::opts_chunk$set(
      dev = "svglite",
      fig.ext = ".svg"
)
```

```{r, warning = F}
data(cars)

ggplot(mtcars, aes(mpg, qsec, color = factor(cyl))) +
      geom_point()

```

Everything works fine, but when I open it in Chrome and try to Inspect Element it turns out that the whole plot is within <img> tags. What I want to achieve is to create rmarkdown doc with html code with the whole ggplot.

I try to use htmlSVG function but it does not work on ggplot. I get an error:

Error in FUN(X[[i]], ...) : argumemt is not a character vector

However, it works very well on basic plot - htmlSVG(plot(data = sampled_df, z ~ price)) when I include it on rmarkdown.

Do you know it is possible to do the same thing with ggplot objects?

1 Answer 1

4

I found a solution. All I had to do is to use svgstring from svglite which generate the whole code and then use htmltools::HTML.

---
title: ""
output: html_document
---

```{r setup, include = FALSE}
library(svglite)
library(ggplot2)
knitr::opts_chunk$set(
      dev = "svglite",
      fig.ext = ".svg"
)
```

```{r, warning = F, echo = F}
data(cars)

s <- svgstring()
ggplot(mtcars, aes(mpg, qsec, color = factor(cyl))) +
      geom_point()

htmltools::HTML(s())

invisible(
      dev.off()
)

```

I use invisible function in order to hide a message generating by dev.off().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.