I was wondering if it is possible to hide a graph with a button like you can do this with a code chunk using code-fold: true
. Is there a similar way for graphs? Here is a reproducible example:
---
title: "How to hide graph by button"
format:
html:
code-fold: true
engine: knitr
---
Example code:
```{r}
library(ggplot2)
ggplot(mtcars, aes(x = qsec, y = mpg)) geom_point()
```
Output:
As you can see you can use a button called "Code" to hide the code chunk. Is there a way to do this only for the graph in Quarto
?
CodePudding user response:
Using a little bit of javascript we can achieve this in Quarto
.
---
title: "How to hide graph by button"
format:
html:
code-fold: true
include-after-body: graph_fold.html
engine: knitr
---
Example code:
```{r}
library(ggplot2)
ggplot(mtcars, aes(x = qsec, y = mpg)) geom_point()
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) geom_point()
print("Its not a graph")
```
graph_fold.html
<script>
function graph_fold() {
cells = document.querySelectorAll(".cell:has(img)");
cells.forEach(cell => {
imgs = cell.querySelectorAll(".cell-output-display:has(p img)");
imgs.forEach(img => {
det = document.createElement("details");
sum = document.createElement("summary");
det.appendChild(sum);
det.children[0].innerText = "Graph";
img_clone = img.cloneNode(true);
det.appendChild(img_clone);
cell.replaceChild(det, img);
});
});
}
window.onload = graph_fold();
</script>