knitr: Add figure notes in .Rmd file - r-markdown

I have a series of .png images that I would like to add notes to in an Rmarkdown document that I am knitting to a .pdf. The basic code for each image looks like this:
```{r certs_coefplot, out.width="100%", fig.cap=fig.4_cap}
knitr::include_graphics("certs_coefplot.png")
```
With beamer slides, I have just inserted some basic latex like this:
\tiny \emph{Notes}: Put Notes here \normalsize
below each code chunk.
But if I try this in the context of a larger document, the notes do not appear below the figure.
A solution involving a custom hook was proposed to a similar question asked here about adding notes to figures in an .Rnw file. In particular, the version where you put the code for the hook at the beginning and then write:
notes = "Notes to explain the plot"
sources = "Explain the sources"
in each chunk seems really convenient.
Is it possible to apply a similar solution an RMarkdown file?

Related

papaja: Changing font sizes and faces for code listings and R output

Based on the answer to this question, I was able to get 2-column papaja with listings wrapping (rather than overflowing column width). But the listings package turns off various features that help code listings and R output stand out relative to the main text.
A simple solution would be if I could globally change the font faces and/or sizes selectively for code and R output. Is there a way to do that in papaja? I haven't been able to figure this out from papaja or Rmarkdown documentation. Thank you!
When you use the listings package in a papaja (or bookdown) document, what is technically happening is that all code is wrapped into an lstlisting LaTeX environment that comes with its own capabilities of customizing code appearance. Hence, you don't see the syntax highlighting that you would otherwise see if you would not use the listings package. The documentation of the listings package with instructions how to style your code can be found here.
To make use of this, you can extend the YAML header of your papaja document like this:
documentclass : "apa6"
classoption : "jou"
output :
papaja::apa6_pdf:
pandoc_args: --listings
header-includes:
- \lstset{breaklines=true,language=R,basicstyle=\tiny\ttfamily,frame=trB,commentstyle=\color{darkgray}\textit}
Here, I first specify the code's language, and use a tiny monospace font. With frame, I add a frame around the code block, and with commentstyle I set comments in italic and gray.

Adding preamble.tex and/or modifying css

Thanks for making papaja. It's really terrific!
I just submitted my first journal article using it and ran into problems. The layout staff don't know what to do with the code chunks and listings that are fine in single-column, full page format, but not in their 2-column format. I'm trying use the class 'jou' option to make 2 columns, but I can't figure out how to control the size of code and listing fonts (possibly by modifying the css, as recommended here), or how to using the latex package 'listings' to set listings to wrap (as recommended here).
I'd be grateful for any advice, and my apologies if I've missed how one might do this in the documentation.
If it's only about getting the listings package to work, you can modify the YAML header that it looks similar to the following:
documentclass : "apa6"
classoption : "jou"
output :
papaja::apa6_pdf:
pandoc_args: --listings
header-includes:
- \lstset{breaklines=true}
However, note that using automatic line breaks will most likely break the code at some points. Therefore, it is worthwhile to consider alternatives: For instance, you could try to use a code style that uses more line breaks. The styler package and add-in might be helpful accomplishing this: https://styler.r-lib.org/

Big graphic makes and white lines in previous page (bookdown/Rmarkdown)

I have added a big PNG (tall, with similar aspect ratio to A4 paper) image in my rmd between two paragraphs using the following chunk (caption was made that way since it will include citations):
(ref:cap-etlm) The ETLM.
```{r etlm, results = "asis", echo = FALSE, fig.cap = "(ref:cap-etlm)", out.width='\\textwidth'}
include_graphics("figures/etlm.png")
````
The problem is, when generating a pdf output, the previous page becomes sparse, with many empty lines (shown with red lines):
This (could) also be the case if the image didn't take the whole page, but was large enough.
How can I let some of the text (that, in the rmd, have been written after the chunk/its reference) appear before the image?
Thanks in advance.
Edit:
This Gist is rmd of a minimal reproducible example (updated screenshot). It also requires csl files, etc., which are in a zip file here on TinyUpload.
Your file template.tex contains the following lines:
\usepackage{float}
\floatplacement{figure}{H}
This forces LaTeX to place figures always HERE, i.e. where they are defined. Removing these two lines solves the problem for me.

RMarkdown - Change Inline Code Color *without changing workflow*

I teach an introductory statistics course using R Markdown in RStudio (Server). We have students knit to html_notebooks, and we often have them use inline code to report various elements of their statistical analyses. It'd be really helpful for grading purposes if we could have the result of inline code output in a different color -- that way we could easily see if they were indeed using inline code or if they copy-pasted a number from their output into raw text.
There's a couple of ideas for solutions posted here, but these won't super work in my case. These are introductory students who are generally kinda afraid of RStudio to begin with, so asking them to do anything complicated with text_spec or sprintf will likely cause mild riots. I really need something that won't change students' workflow at all.
I wonder if there's any way to configure things either on the backend in RStudio Server (maybe by messing with knitr?), or through some kind of <style> tag wizardry in the preamble, so that inline code will print its results in a different color.
Thanks!
EDIT: Arthur Berg below has provided something that's almost exactly what I need. Here's a MWE:
---
title: "test knit_hook"
output: html_document
---
```{r, setup, include="FALSE"}
knitr::knit_hooks$set(inline=function(x){paste0("<span style=\"color: #0000FF;\">",
x,"</span>")})
```
`r pi`
The only issue with this is that it doesn't work if I change to html_notebook in the YAML header and thus use the "Preview" button in the RStudio IDE. For external reasons, it's important for us to have the output type as html_notebook. Anyone know how we might modify this to get it to work with html_notebook?
A way to achieve this without changing the workflow too much is to create your own format (e.g. html_notebook2) that is derived from the original but modifies the inline hook of knitr.
To get started you can check out this document.
Basic steps include
Create a new R package
Within this project run usethis::use_rmarkdown_template(). This creates the folder structure for your new format.
Edit skeleton.rmd and template.yaml
Define your format in a R file which has the same name html_notebook2.R(kind of a convention).
The content of the html_notebook2.R file could be
#'#import knitr
set_hooks <- function() {
default_hooks <- knit_hooks$get()
list(
inline = function(x) {
paste0("<span style=\"color: #FF0000;\">", x,"</span>")
})
}
#' #importFrom rmarkdown output_format knitr_options pandoc_options html_notebook
#' #export
html_notebook2 = function() {
output_format(
knitr = knitr_options(knit_hooks = set_hooks()),
pandoc = pandoc_options(to = "html"),
clean_supporting = FALSE,
base_format = html_notebook()
)
}
In the first part we define a new inline hook which only changes the font color.
The second part is the definition of the new format.
After building and installing the package you can create a new rmarkdown document and use output: packagename::html_notebook2 as the output format. All inline code output will be colored red using my code. Here is an example:
---
title: "Inline"
output: cformat::html_notebook2
---
## R Markdown
`r pi`
I created such a package and you can find it on GitHub. Feel free to copy it and rename it (cformat is a pretty lame working title ;) ).
Notice though that your students could change the color manually using HTML/CSS anyways. A way around could be some kind of key generation using a certain rule (unknown to the students obviously). For each inline chunk a key is generated and embedded using
paste0("<span code=", key," style=\"color: #FF0000;\">", x,"</span>")
If a valid key is embedded, the output was generated using R and not simply copied.
For those looking for a fix to a simple R markdown document, adding this line changes the inline output to blue.
knitr::knit_hooks$set(inline=function(x){paste0("<span style=\"color: #0000FF;\">", x,"</span>")})

Changing citation style to number-letter in papaja Rmarkdown package

I'm writing a scientific manuscript in RMarkdown using the papaja package, which enables me to report my statistics beautifully. However, the journal now requires me to submit a Word document with number-letter referencing. Is it possible to change the referencing style to a number-letter style in Papaja?
I tried opening the LaTeX output from papaja, but it has the citations set out in the text in APA format (e.g. "Apthorp, Bolbecker, Bartolomeo, O'Donnell, \& Hetrick, 2018"), which is not useful to me.
Here's the code from the top of the manuscript:
bibliography : ["PD_sway-1.bib"]
floatsintext : no
figurelist : no
tablelist : no
footnotelist : no
linenumbers : yes
mask : no
draft : no
documentclass : "apa6"
classoption : "man"
output : papaja::apa6_pdf
It would be great if I could get a Word document with number-letter referencing that I could then edit, but a LaTeX file or PDF with the correct citation format would be fine too.
The references are already typed out in APA style in the LaTeX document because they are handled by pandoc-citeproc rather than LaTeX. This has the advantage that the automatic reference formatting also works when you output your document in Word format. To get a Word document all you need to do is change the output line in the YAML front matter:
output: papaja::apa6_docx
Note that the formatting of Word documents that pandoc supports is somewhat limited and you may have to fix some things manually. From the corresponding section in the papaja manual:
More over, rendered documents in DOCX format require some manual work before they fully comply with APA guidelines.
We, therefore, provide the following checklist of necessary changes:
Always,
add a header line with running head and page number
If necessary,
position author note at the bottom of page 1
move figures and tables to the end of the manuscript
add colon to level 3-headings
in figure captions,
add a colon following the figure numbers and italicize(e.g. "Figure 1. This is a caption.")
in tables,
add horizontal rules above the first and below the last row
add midrules
Changing the citation style works just as it does in any R Markdown document. The work-in-progress papaja manual has a section on this:
Other styles can be set in the YAML front matter by specifying a CSL, or Citations Style Language, file. You can use either one of the large number of existing CSL files, customize an existing CSL file, or create a new one entirely.
To change the citation style, download the CSL file and add the following to the YAML front matter:
csl: "path/to/mystyle.csl"
I'm not sure what style the journal requires but most likely a corresponding CSL file already exists.