How to hide a Graph with button in Quarto? - r

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?

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>

Related

Scrollbar for output chunk in Quarto

I would like to plot multiple plots from a chunk and add a scrollbar to the output of that chunk. I see here that this could be done for Code Overflow, but I am not sure how to scroll the output instead of adding all the plots below each other like in the example below:
---
title: "Scrollbar in output chunk"
format:
html:
code-overflow: wrap
---
Here is some example code:
```{r}
#| code-overflow: wrap
library(ggplot2)
for(i in unique(iris$Species)) {
print(
ggplot(iris[iris$Species == i, ], aes(x = Sepal.Length, Sepal.Width)) +
geom_point()
)
}
```
Output:
As we can see from the output, all the plots are shown below each other, but I would like to have a scrollbar chunk so it doesn't show all plot at once. So I was wondering if anyone knows how to add a scroll option to the output of a chunk in Quarto?
You can create a css file with a defined max-height and overflow-y and add it to your chunk with class. Note that this will also include the code in the scrolling section. Also note that if you want a text output to be scrollable, you should use class-output instead of class in your chunk options.
---
title: "scrollable-output"
format: html
---
```{css, echo = FALSE}
.output {
max-height: 500px;
overflow-y: scroll;
}
```
Here is some example code
```{r}
#| class: output
library(ggplot2)
for(i in unique(iris$Species)) {
print(
ggplot(iris[iris$Species == i, ], aes(x = Sepal.Length, Sepal.Width)) +
geom_point()
)
}
```
You can add a div before the chunk, e.g.
---
title: "Scrollbar in output chunk"
format: html
css: styles.css
---
Here is some example code:
:::{.scrolling}
```{r}
library(ggplot2)
for(i in unique(iris$Species)) {
print(
ggplot(iris[iris$Species == i, ], aes(x = Sepal.Length, Sepal.Width)) +
geom_point()
)
}
```
:::
styles.css
.scrolling {
max-height: 500px;
overflow-y: auto;
}
If you do not want the scrolling for the code, than you could do this:
---
title: "Scrollbar in output chunk"
format: html
css: styles.css
---
Here is some example code:
```{r}
#| eval: false
library(ggplot2)
for(i in unique(iris$Species)) {
print(
ggplot(iris[iris$Species == i, ], aes(x = Sepal.Length, Sepal.Width)) +
geom_point()
)
}
```
:::{.scrolling}
```{r}
#| echo: false
library(ggplot2)
for(i in unique(iris$Species)) {
print(
ggplot(iris[iris$Species == i, ], aes(x = Sepal.Length, Sepal.Width)) +
geom_point()
)
}
```
:::

Referencing issue for Rmarkdown

I'm trying to link figures throughout my R Markdown file and I keep getting the error when I try to knit the profile:
[WARNING] Citeproc: citation Picture not found
Further, when I try to cite using #chunk-name, the output produces a result such as chunk-name? with a question mark.
I have tried to solve this error by downloading pandoc due to some internet searching but absolutely nothing has helped me. Anything regarding this error message would be helpful.
I have attached a code of my YAML if it's of any help:
Apologies I don't know how to attach it as a code without the lines coalescing.
Example of GG Plot I was trying to create:
```{r Picture , fig.asp=0.5, out.width= "100%", warning=FALSE, message=FALSE, fig.cap= " Student's grade count vs planning "}
library(ggplot2)
ggplot(qn1frame, aes(x=(hourly_plan), fill=category
)) + geom_bar() + theme_bw(base_size = 12) + scale_fill_brewer(palette = "Set1") +
labs(fill = "Grades", y = "Proportion", x = "ewuhrwe") + plot_layout(guides = 'collect') +
plot_annotation(tag_levels = 'A')
ggplot(qn1frame, aes(x=(hourly_plan), fill=category
)) + geom_bar(aes(stat="identity"), position= "fill") + theme_bw(base_size = 12) + scale_fill_brewer(palette = "Set1") +
labs(fill = "Grades", y = "Proportion", x = "Occupational exposure (yrs)") + plot_layout(guides = 'collect') + plot_annotation(tag_levels = 'A')
```
How I've been trying to create a citation back to this graph:
Testing captions:
Referring to #Picture..
However, I get the WARNING output when I render the file as well as in the actual code I get: (Picture?) when I tag it. Any help would be immensely helpful.
Thank you!
You are having the question mark sign ?? instead of a reference because you are trying to refer from a code chunk that generates two figures. So when you use `#ref(fig:chunk-name) to refer to the figures, it gets confused as to which figure to refer to.
So one option could be using a separate chunk for each plot. Or if you want to generate multiple plots from the same chunk, you need to refer them with \#ref(fig:chunk-name-1), \#ref(fig:chunk-name-2) etc.
Reproducible Example
---
title: "Cross Referencing"
output:
bookdown::html_document2:
self_contained: yes
code_folding: hide
code_download: yes
toc: yes
toc_float: yes
number_sections: yes
fig_caption: TRUE
link-citations: true
link-references: true
date: "2022-09-16"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
```
## R Markdown
```{r}
#| cars-plot,
#| fig.cap=c("Displacement vs Miles per gallon", "HP vs Miles per gallon"),
#| echo=FALSE,
#| fig.height=3,
#| fig.width=4
ggplot(mtcars, aes(mpg, disp)) +
geom_point()
ggplot(mtcars, aes(mpg, hp)) +
geom_point()
```
Testing captions:
Referring to \#ref(fig:cars-plot-1) and \#ref(fig:cars-plot-2)

How to add a curly close quote or apostrophe to plot text when knitting to pdf?

I am currently plotting some data from a survey question to be used in a book. It would be useful to put typographically-correct curly quotes or what are sometimes called "smart" quotes around the survey question on the x-axis.
When creating a plot in R markdown, however, it is easy to create a typographically-correct open curly quote or apostrophe with back-tics (e.g., using one or two back-tics will create a curly ‘ or “ vs straight ' or ") but it is not obvious how to add a curly close apostrophe or quote (e.g., ’ or ”). I assume the solution is simple but was unable to figure it out via options like plotmath and hardcoding curly quotes with something like labs(x = '“some text”') didn't work. Other options like sQuote() or dQuote() work interactively but, when knitting to pdf, the curly quotes get converted to straight quotes.
How can I add a curly close quote or apostrophe to plot text when knitting in R markdown to pdf?
---
title: "Curly Quote in Plot Example"
output: pdf_document
date: "2022-08-17"
---
```{r}
library(ggplot2)
ggplot(mtcars) +
aes(x = hp, y = mpg) +
geom_point() +
labs(x = "`Is MPG related to HP?`")
```
One way we can add curly quotes on the x-axis title is by using HTML code and then render it using element_markdown from {ggtext} package.
---
title: "Curly Quote in Plot Example"
output:
pdf_document:
dev: cairo_pdf
date: "2022-08-17"
---
```{r}
library(ggplot2)
library(ggtext)
ggplot(mtcars) +
aes(x = hp, y = mpg) +
geom_point() +
labs(x = "‘Is MPG related to HP?’")+
theme(
axis.title.x = element_markdown()
)
```
The x-axis title looks like this now,
You could use the cairo_pdf device. You can add dev="cairo_pdf" to your chunk and then use ggtext with element_markdown like this:
---
title: "Curly Quote in Plot Example"
output: pdf_document
date: "2022-08-17"
---
```{r, dev="cairo_pdf"}
library(ggplot2)
library(ggtext)
ggplot(mtcars) +
aes(x = hp, y = mpg) +
geom_point() +
labs(x = "‘Is MPG related to HP?’")+
theme(axis.title.x = element_markdown())
```
Output:

Hover to show image or icon in ggplot2 (R markdown)

I am fascinated by dynamic or interactive ggplot graphs. I found some easy hover options with ggiraph at https://davidgohel.github.io/ggiraph/ Here is a MWE for R markdown:
---
title: "Hover"
author: "Author"
output: html_document
---
## Hover ggplot2
```{r, warning=FALSE, message=FALSE}
library(ggplot2)
library(ggiraph)
data <- mtcars
data$carname <- row.names(data)
gg_point = ggplot(data = data) +
geom_point_interactive(aes(x = wt, y = qsec, color = disp,
tooltip = carname, data_id = carname)) +
theme_minimal()
girafe(ggobj = gg_point)
```
Is there any possibility to show a small image or icon when hover over a datapoint in a ggplot in markdown? I wonder how and where I would store these images. I would like to give every data point a specific image. I am working on famous painters, i.e. assume that I have very few data points in a scatterplot. Thus when people hover on "The Scream", they should see a little version of https://en.wikipedia.org/wiki/List_of_most_expensive_paintings#/media/File:The_Scream_Pastel.jpg

R markdown linking to a figure

I am creating a report with multiple figures and tables. I'd like to refer to them in the accompanying text. I've tried the following:
---
title: "Test"
output:
pdf_document
---
Figure \ref{test} is a graph
```{r test, fig.cap="This is a graph"}
df <- data.frame(gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30))
ggplot(df, aes(x = gp, y = y)) +
geom_point()
```
This is text to follow the diagram
\pagebreak
This is another page but can still link to Figure \ref{test}
But the result is:
Figure ?? is a graph
...
This is another page but can still link to Figure ??
Is there a default way to do this in R markdown without having to write functions myself
I think I found an answer here- https://github.com/yihui/knitr/issues/323
Using this code seemed to provide the behavior I think you're looking for, if I'm understanding correctly.
---
title: "Test"
output:
pdf_document
---
Figure \ref{fig:plot} is a graph
```{r plot-ref, fig.cap = "This is a graph\\label{fig:plot}"}
library('ggplot2')
df <- data.frame(gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30))
ggplot(df, aes(x = gp, y = y)) +
geom_point()
```
This is text to follow the diagram
\pagebreak
This is another page but can still link to Figure \ref{fig:plot}

Resources