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?
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.
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).
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With