I've built a function in rmarkdown to produce some HTML output with given values, but I want it to work if one of the passed values references a ggplot object.
Basically, knitr renders this perfectly:
x <- [R computation]
y <- [ggplot figure]
<div id="some_number">`r x`</div>
<div id="some_figure">
```{r}
y
```
</div>
But I don't want to have to rewrite that every time I use that particular chunk of html with different x and y. So I wrote the following function:
html_func <- function(x,y) {
template <- "
<div id=\"some_num\">{x}</div>
<div id=\"some_fig\">{y}</div>
"
instance <- glue::glue(template)
output <- knitr::asis_output(instance)
return(output)
}
number <- [R computation]
figure <- [ggplot figure]
html_func(number, figure)
The rendered page shows the "number" computed correctly within the div, but doesn't render the plot.
How can I get it to produce the plot within the HTML container?
UPDATE: Commenter suggested using live data so here we go.
This works:
```{r}
library(ggplot2)
data(mtcars)
number <- mean(mtcars$mpg)
figure <- ggplot2::ggplot(mtcars, aes(x=hp, y=mpg)) +
geom_point()
```
<div id="some_number">`r number`</div>
<div id="some_figure">
```{r echo=FALSE}
figure
```
</div>
But this does not. The computation outputs fine, but the plot does not render.
```{r}
library(ggplot2)
data(mtcars)
number <- mean(mtcars$mpg)
figure <- ggplot2::ggplot(mtcars, aes(x=hp, y=mpg)) +
geom_point()
html_func <- function(x,y) {
template <- "
<div id=\"some_num\">{x}</div>
<div id=\"some_fig\">{y}</div>
"
instance <- glue::glue(template)
output <- knitr::asis_output(instance)
return(output)
}
html_func(number, figure)
```
Here's a screenshot comparing the two.

print()for the plot. That would be necessary in aresults = "asis"style chunk, anyway.print(figure)instead of justfigurebut it appears you also still get the printed object. Are you attached toknitr::asis_output()or would you consider using aresults = "asis"chunk? I've never used one for writing HTML with R output, though, only markdown, so maybe that's a problem.print(figure)produced the plot, but not rendered within the HTML container, and the printed object still appears. I'm not married toknitr::asis_output()but doing{r results="asis"]produces the same thing.