Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show ggplot objects in rmarkdown as html svg code

Tags:

r

ggplot2

svg

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?

like image 793
Nicolabo Avatar asked Sep 28 '16 19:09

Nicolabo


People also ask

How do I show plots in R markdown?

In RStudio, when you open a new RMarkdown file, in the editor pane, there is a cogwheel button / menu where you can choose "Chunk Output Inline". That should put the plots into the document.

How to include code in RMarkdown?

You can insert an R code chunk either using the RStudio toolbar (the Insert button) or the keyboard shortcut Ctrl + Alt + I ( Cmd + Option + I on macOS).

How do I convert R to R markdown?

If you use the RStudio IDE, the keyboard shortcut to render R scripts is the same as when you knit Rmd documents ( Ctrl / Cmd + Shift + K ). When rendering an R script to a report, the function knitr::spin() is called to convert the R script to an Rmd file first.


1 Answers

I found a solution. All I had to do is to use strstring 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().

like image 100
Nicolabo Avatar answered Oct 18 '22 02:10

Nicolabo