Quarto bridges the gap between raw R
scripts and polished, meaningful reports. It empowers you to blend code, narrative, visualizations, and results in one cohesive and dynamic document. 🔥
This guide is a complement to my productive R workflow mini course. It is packed with valuable tips and tricks to elevate your Quarto documents, turning them into visually stunning and insightful reports. When exporting to HTML
, you unlock the full potential of web-based interactivity and design.
2
5
12
15
Quarto uses Markdown
under the hood. Markdown
is a lightweight markup language for creating formatted text using a plain-text editor. It is very intuitive for text styling.
For instance, typing **hello**
in your .qmd
file translates to hello in the HTML output.
The key styles in Markdown are simple to master:
Format | Code | Result |
---|---|---|
bold | **hello** | hello |
italic | *hello* | hello |
underline | <u>hello</u> | hello |
strikethrough | ~~hello~~ | |
code | `hello` | hello |
You should use this syntax extensively. It makes your document much more "alive"
You can see a document using this technique here, and the original .qmd
file here.
A very common need, helping browsing your document efficiently.
Fortunately this is very straightforward: you just have to specify it using the toc
the header of the document. This is how the header would look like:
---
title: "Your title"
format: html
editor: visual
toc: true
---
As a result, your TOC will look like this in your document.
I have a strong preference for minimalist documents with ample spacing. This design approach ensures readability and visual appeal.
A practical method for delineating sections in a document is by using a horizontal line separator. This can be easily achieved by inserting three asterisks: ***
or a set of dashes: ---------
.
This action generates an HTML hr
element, which appears as a horizontal line, as demonstrated below:
Additionally, you can place this line beneath titles to accentuate them and add a touch of professionalism.
A very common need, helping browsing your document efficiently.
Fortunately, this is very straightforward: you just need to specify it in the document's header. Here's an example of what the YAML header should look like:
---
title: "Your Document Title"
number-sections: true
---
By adding this to your YAML header, each title in your Quarto document will automatically be prefixed with the correct numbering, streamlining the organization and navigation of your document.
You can create a html
file with some content. And then display it at the bottom of your quarto doc.
First, create a file called footer.html
file. Copy the following in it:
<hr />
<p style="text-align: center;">A work by <a href="https://github.com/holtzy/">Yan Holtz</a></p>
<p style="text-align: center;"><span style="color: #808080;"><em>Yan.holtz.data@gmail.com</em></span></p>
<!-- Add icon library -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Add font awesome icons -->
<p style="text-align: center;">
<a href="https://twitter.com/r_graph_gallery?lang=en" class="fa fa-twitter"></a>
<a href="https://www.linkedin.com/in/yan-holtz-2477534a/" class="fa fa-linkedin"></a>
<a href="https://github.com/holtzy/" class="fa fa-github"></a>
</p>
You might not know how to write some html to fit your desired footer. Just ask ChatGPT!
Now, we need to say to Quarto to use this file as a footer. To do so, change the header of your quarto doc as follow:
---
title: "Report with a footer"
include-after-body: "footer.html"
---
Render your document! You should get this at the bottom:
Personal preferences in document design play a significant role in readability and aesthetics. I find that adding a bit of space above the titles enhances the document's overall appearance. It not only introduces a breathing space but also makes it easier to distinguish between different sections.
Achieving this effect is straightforward with the use of a custom style sheet. This style sheet will contain rules specifically designed to add extra space above the headings.
Begin by creating a CSS file named style.css
and include the following rules:
h1, .h1, h2, .h2, h3, .h3 {
margin-top: 84px;
}
These CSS rules will add a margin of 84 pixels above your level 1, 2, and 3 headings (represented by h1
, h2
, and h3
tags, respectively).
Finally, to apply these styles to your Quarto document, you'll need to link this stylesheet. This is done by modifying the document's header to include the style.css
file.
---
title: "A doc with space before titles"
format: html
css: style.css
editor: visual
---
The result will look like this. Of course, feel free to change the gap size to your convenience!
You can add context to your figure by adding a caption below it. To do so, simply use the fig.cap
argument in the code chunk header:
{r, fig.align="center", fig.width=6, fig.height=6, fig.cap="Figure: Here is a really important caption."}
# Code for your graph
Note that I like to center my caption and image. To do so, you can add this inline style at the top of your doc. (you can also add it in an external .css
style sheet of course)
<style>
figcaption {
text-align: center;
}
</style>
Here is an overview of a quarto doc with a ggplot2 chart and its caption:
Let's say you are in the Conclusion
section of your doc. And you want to reference something that happened in section 2
.
First, you have to give an id
to the title you want to target. For instance, your second title could be added this way. It adds a title "Data wrangling" with the id #section-2
.
# Data wrangling {#section-2}
Second, add a link to this title! For instance, in my conclusion I can write this sentence:
Here is the link to the [section 2](#section-2) of the document!
And that's it! You can try it in the following document. Scroll to the conclusion section and click the link!
It is very easy to insert an interactive table in your document thanks to the DT package. The output allows to filter rows, search for something and sort using a specific columns!
Install the library with install.packages("DT")
. Then, just pass a dataframe to the datatable()
function to get a stunning interactive output!
Code:
library(DT)
data(iris)
# Make a table
datatable(iris, filter = "top")
Result:
Sometimes you want to save some real estate in your doc. Using tabs, you can let the reader browse whatever he is interested in!
This is how to use tabs in your Quarto doc:
::: {.panel-tabset .nav-pills}
## Scatterplot
Content that will show under first tab
## Boxplot
Content that will show under first tab
## Barplot
Content that will show under first tab
:::
Explanation: in a quarto doc, the :::
operator adds a html div
. Then, writing .panel-tabset .nav-pills
adds 2 classes to the div
. Quarto relies on a framework called bootstrap. Bootstrap knows thoses classes and transform their children in tabs automatically for us!
Sometimes code just takes too much space in your doc. If readers are not interested in it, it can make them lose focus.
You can very easily hide this code, and add a button to reveal it if necessary. Just use those options in the Quarto report header:
---
title: "Hide code in report"
format:
html:
code-fold: true
code-summary: "Show the code"
---
Check the result below, there is now a Show the code
button!
Note that you can also use the code-tools: true
option to include a Code menu that allows to show or hide all the code chunks in one shot.
Sometimes a chart is just too small to be read in your quarto report. Or maybe you want to display several charts side by side, with the option to enlarge one of them.
It is definitely possible to open a chart in fullscreen mode!
To do so, first create a button using some HTML code:
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">See in Full Screen</button>
Second, create a div
with the modal content that is your chart:
<div class="modal fade" id="exampleModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered p-8" style="max-width: 90%"><div class="modal-content">
```{r, echo=FALSE, warning=FALSE, out.width="100%"}
scatter_plot
```
</div></div></div>
And that's it. You now have a See in Full Screen
button allowing to enlarge the chart. You can try it in the box below, but the result will be more satisfying in this online report.
Your quarto report is an HTML file: it is basically a little website! 🎉
As a result, you can include interactive charts in it. There is an R package that is magical for this: plotly.
Plotly can turn any ggplot2 chart to an interactive chart with just 1 additional line of code!
Check the following example:
# Usual area chart
p <- data %>%
ggplot( aes(x=date, y=value)) +
geom_area(fill="#69b3a2", alpha=0.5) +
geom_line(color="#69b3a2") +
ylab("bitcoin price ($)") +
theme_ipsum()
# Turn it interactive with ggplotly
p <- ggplotly(p)
p
And that's it!
Now you can hover the chart to get a tooltip, zoom on a specific area, double click to zoom-out and more!
Adding dark mode support is pretty straightforward. You just have to specify it in the YAML header of the quarto report.
Note that the first mode that you specify will be the default. (here dark is on top, so it is the default)
---
title: "Dark Mode"
format: html
editor: visual
theme:
dark: darkly
light: flatly
---
And that's the result!
When you click the render
button, your quarto .qmd
file is read and transform into a HTML file.
This is basically a little website! You can open it in a browser like firefox!
As a result, you can publish it online! It means you won't have to send it by email anymore. You will just have to share the URL.
How to do this?
index.qmd
and index.html
Settings
→ GitHub Pages
&rarr Source
→ Master Branch
→ Save
.That's it, your URL will be available soon!
If this explanation sounds confusing no worries! It is exactly what you can learn in the module 5 of the productive r workflow course!
Note that all the quarto "Full Report" examples are built using this exact same technique!
ggiraph
is one of the most powerful R package when it comes to interactive data visualization.
One feature I really like is the ability to connect 2 charts together.
Since quarto supports interactive outputs, let's make the most of it! In the example below, you can hover over a circle on the map to highlight a line on the chart (and reciprocally)! ❤️
Use callouts to draw attention to important complementary content without interupting the document flow.
5 types of callout exist out of the box, and they are really easy to use. Here is an example with a note
callout:
:::{.callout-note}
This is an example of an tip callout
:::
You can also try with tip
, caution
, warning
and important
.
Note that you can also customize a callout using css
! Check the shaking callout below:
You can add any type of content in the margin of the document.
If the content you want to display is generated by R, use the #| column: margin
option:
```{r}
#| column: margin
knitr::kable(
mtcars[1:3, 1:3]
)
```
If the content you want to display is not made in a code chunk, apply the .column-margin
class to the div:
::: {.column-margin}
Hi! I'm a side note!
:::
Full reference available here.
Sometimes you want a graph to be big, wider than the narrow text area!
It is totally doable thanks to the column
and out-width
options
```{r}
#| column: screen
#| out-width: 100%
... your graph(s) here
```
The example below is a bit disappointing since the iframe is narrow. Check the online example!
sessionInfo()
is a R command that tells you everything about your working environment: R version, packages in use and their versions, and more.
It is a very good practice to include it at the end of your report. This way, people will be able to run your work again in 10 years.
The result is pretty ugly though. I suggest to hide it in an accordion as follow:
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" >Session Information</button><div id="collapseOne" class="accordion-collapse collapse"><div>
```{r}
sessionInfo()
```
</div></div>
Check the result below!
Note: for better reproducibility, you should definitely check the renv
package!
You can add automatically numbered footnotes like this:
For instance, here is one attached to the word carrot^[The carrot (Daucus
carota subsp. sativus) is a root vegetable, typically orange in color].
Check the result below!
You can add a background color or an image below the title thanks to the title-block-banner
argument of the YAML header:
---
title: "A title with a background"
subtitle: "And a subtitle"
format: html
title-block-banner: "#f0f3f5"
title-block-banner-color: "black"
---
Check the result below!
People who read your doc are not necessarily familiar with your syntax.
Thanks to the doc-link option, you can transform your functions in hyperlinks, linking to their official documentation. 🔥
Start by installing the xml2
and downlit
packages. Then use this in your YAML header:
---
title: "Quarto Computations"
format:
html:
code-link: true
---
Try clicking on the functions in the code of the report below!
In web development, parallax refers to a technique where background images move at a different speed than the foreground content as the user scrolls down or across a webpage.
You can create such an effect by adding the following div
in your content:
<div class="parallax-container"><div class="parallax-image-container"></div></div>
And then apply some CSS to it to make the image appear.
.parallax-container {
position: relative;
}
.parallax-image-container {
background-image: url(https://github.com/holtzy/dataviz-inspiration/blob/main/public/misc/overview1.png?raw=true);
height: 200px;
background-attachment: fixed;
opacity: 1;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
Your Quarto doc is probably linked with a Github Repository. (At least, it should 🙃). It is a good practice to add a link to it: people can be interested in contributing to your code.
1️⃣ Create an html file called github-corner.html
in your folder. In this file, place this content and don't forget to update the link at the beginning. Note that this code comes from this open-source project.
2️⃣ Include this file in the document header thanks to the include-in-header
YAML header option:
---
title: "Add a Github Corner"
format:
html:
include-in-header:
- file: github-corner.html
editor: visual
---
Here is the result!
The octocat even shakes his arm on hover 😀!
Note: link does not work above because it's an iframe, but works on the online document.
The Leaflet package enables the creation of interactive maps directly within R.
It's incredibly easy to use, and you can find numerous tutorials in theR Graph Gallery.
When using HTML output, the interactive map will be seamlessly integrated into your report, allowing users to zoom and pan just like on a Google Map.
library(leaflet)
leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng = 174.768, lat = -36.852, popup = "The birthplace of R")
Here is the result!
Simply add the code-link
option to your document header to activate this feature.
Once enabled, all function names in your code chunks will become clickable links that direct to their respective documentation. This is incredibly useful for readers who want to quickly understand the functions you're using in your work.
---
format:
html:
code-link: true
---
Here is the result!
It is possible to add some information about the code you write, without cluttering the code chunk.
In the example below, hover over the little numbers on the right (1
and 2
). It will reaveal a little tooltip with some explanation about the code line 🔥.
Two steps are required to trigger this feature. The code below shows how it works:
```{r, warning=F, message=F}
library(dplyr) # <1>
mtcars_summary <- mtcars %>%
filter(cyl == 6) %>%
select(mpg, hp, wt) %>%
summarise(
avg_mpg = mean(mpg), # <2>
avg_hp = mean(hp),# <2>
avg_wt = mean(wt)# <2>
)
```
1. `dplyr` is one of the cornerstone of the tidyverse, really useful for data wrangling.
2. here I'm computing 3 variables, the averages of `mpg`, `hp` and `wt`
Here is the result!
Particle.js is a javascript library that creates beautiful particle animations. It is possible to use it to customize the background of your document header!
This is possible thanks to HTML partials: we provide a snippet of HTML code that will be used instead of the usual HTML of regular quarto doc. In this partial, we call the particle.js library.
This is how the partial looks like:
<header id="title-block-header" style="position: relative">
<!-- This is the div in which the particles will be included -->
<div id="particles-js"></div>
<!-- Actual content on top of the particles-->
<div class="title-block-content">
...content goes here...
</div>
<!-- Particle.js script loaded from a CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/particles.js/2.0.0/particles.min.js"></script>
<!-- use the particle js library with our own config (json file). -->
<script>
particlesJS.load("particles-js", "./particles.json");
</script>
</header>
And here is the result!