R markdown linking to a figure - r

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}

Related

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)

RMarkdown and ggplot: Axis labels cut off

In an RMarkdown PDF document, I am generating a heatmap with rather long tick labels. For some reason, this causes the y-axis label and the colour legend to be cut off. I already attempted several tricks in order to fix this, but so far to no avail. Here is my reprex:
---
title: "Test"
output: pdf_document
draft: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = FALSE, fig_crop=FALSE
)
```
```{r dependencies, include=FALSE}
library(tidyverse)
options(print_format="tex")
```
```{r, include=FALSE}
# Dummy data
set.seed(1234)
Count = rep((1:5), 8)
Gadget = rep(c("BANANA", "APPLE", "PEAR", "ORANGE", "ENCYCLOPEDIA", "XYLOPHONE", "TOMATO", "POTATO"), each=5)
GadgetScore = runif(40, 0, 100)
data = data.frame(Count, Gadget, GadgetScore)
```
```{r}
# Generate heatmap
maxi = max(data$GadgetScore, na.rm=TRUE)
mini = min(data$GadgetScore, na.rm=TRUE)
midi = mini+(maxi-mini)/2
ggplot(data, aes(Count, Gadget, fill=GadgetScore)) + geom_tile() +
scale_fill_gradient2(name="Gadget score value", low="red", mid="yellow", high="green", midpoint=midi) +
labs(x="Count", y="Gadgets")
```
Here is the output:
As you can see, the y-axis label Gadgets on the left hand side, and the colour legend label Gadget score value on the right hand side are cropped. As I said, I already tried a couple of hints from StackOverflow, but so far, none of them worked.
Trick 1: Following this post, I tried adding
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
to the ggplot elements.
Trick 2: Following this post, I tried to adapt the width of the plot chunk with something like
fig.width = 5
Trick 3: Following this post, I tried adding
theme(plot.margin = margin(100, 100, 100, 100))
to the ggplot elements.
Trick 4: I tried adding the option crop = FALSE and fig_crop=FALSE to the setup chunk.
Unfortunately, none of these tricks worked. Any help will be much appreciated.
In my case, the cropping error was related to a deprecated version of GhostScript. After updating GhostScript to the latest version (9.54.0), I can run the reprex without any image cropping issues.
The code works perfectly for me. However, you can check the alignment of the image, maybe if you place it a bit more to the right you can see the label. For this try in the last chunk to add {r, fig.dim = c(5, 2.5), fig.align = 'right'}

RMarkdown not printing Chinese characters in graphs

---
title:
output:
pdf_document:
latex_engine: xelatex
fontsize: 11pt
#mainfont: Calibri
classoption: letter
geometry: left=0.5in, right=0.5in, top=0.6in, bottom=1.25in
subparagraph: yes
header-includes:
- \usepackage[UTF8]{ctex}
- \usepackage{setspace}
- \usepackage{tocloft}
- \usepackage{anyfontsize}
- \usepackage{fancyhdr}
- \usepackage{fontspec}
- \usepackage{sectsty}
- \sectionfont{\huge}
- \subsectionfont{\fontsize{14}{16.8}\selectfont}
- \pagestyle{fancy}
- \renewcommand{\headrulewidth}{0pt}
---
```{r}
library(ggplot2)
print("中文")
df <- data.frame(
gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30)
)
ds <- plyr::ddply(df, "gp", plyr::summarise, mean = mean(y), sd = sd(y))
# The summary data frame ds is used to plot larger red points on top
# of the raw data. Note that we don't need to supply `data` or `mapping`
# in each layer because the defaults from ggplot() are used.
ggplot(df, aes(gp, y)) +
geom_point() +
geom_point(data = ds, aes(y = mean), colour = 'red', size = 3) +
labs(x = "中文")
```
After knitting this file, it seems that the character encoding works fine for the print function, but the Chinese characters do not show up in graph labels, and I get errors on character conversions. I am a Mac user.
TL;DR: This doesn't appear to be a knitr/rmarkdown issue, but rather an issue related to both the font and the output device. I'm not sure of the cause, but the workaround below involves changing the output font (Batang worked for me) and the output device (pdf is the default, but changing to cairo_pdf or png both worked for me).
First, identify a font family for which R will render the characters properly. I'm not sure in general how to determine this without trial and error, but in the past I've found that the Symbola and Batang fonts often seem to work with non-English characters and various unicode symbols. You'll need to install the fonts on your computer if you don't have them, and you also might need to use the extrafont package to register the fonts in R. Then you can run the plot code in the console and see if the Chinese characters render properly.
With the Batang font, I found that I was able to output plots to the console with the Chinese characters rendered properly. However, the standard pdf device failed to render the characters, whether saving the plot to pdf interactively or when knitting. Instead I tried the cairo_pdf and png devices and these both worked. Here's example code (using the same yaml as in your question):
```{r, include=FALSE}
knitr::opts_chunk$set(echo=FALSE)
library(ggplot2)
```
```{r, dev="cairo_pdf"}
df <- data.frame(
gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30)
)
ds <- plyr::ddply(df, "gp", plyr::summarise, mean = mean(y), sd = sd(y))
ggplot(df, aes(gp, y)) +
geom_point() +
geom_point(data = ds, aes(y = mean), colour = 'red', size = 3) +
labs(x = "中文", title="cairo_pdf device") +
#theme(axis.title.x=element_text(family="Batang")) # To change font only for x-axis title
theme(text=element_text(family="Batang", size=15))
```
```{r, dev="png", dpi=400}
ggplot(df, aes(gp, y)) +
geom_point() +
geom_point(data = ds, aes(y = mean), colour = 'red', size = 3) +
labs(x = "中文", title="png device") +
theme(text=element_text(family="Batang", size=15))
```
And here's what the plots look like in the output document:

Size of font in ggplot plot changes in relation to plot using knitr

I'm using knitr for the first time, and have a problem concering the font size in ggplot plots. This is an example plot:
d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)
In knitr I have the same plot in a chunk in my R markdown:
---
title: "Untitled"
output: html_document
---
```{r, echo=FALSE}
library(ggplot2)
d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)
```
The plot looks fine in RStudio or when saved with ggsave(). However the numbers in the plot in the resulting knitr html have a much larger font size, in total and relative to the plot size:
In this example it does not matter much, but in my data the numbers start to overlap each other / run out of their cells.
An added complication is that the plot is done by a package, so I can't easily change the size option in the stat_sum call.
Try adjusting fig.height and fig.width:
---
title: "Untitled"
output: html_document
---
```{r, echo=FALSE,fig.height=10,fig.width=10}
library(ggplot2)
d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)
```
If you want don't want the figure to be as large, you can adjust out.height and out.width:
---
title: "Untitled"
output: html_document
---
```{r, echo=FALSE,fig.height=10,fig.width=10,out.height=600,out.width=600}
library(ggplot2)
d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)
```

Raw HTML and plots in a (knitr) loop

I am putting together a Knitr script to generate a report. The content of the report is determined dynamically at runtime, where sections of the report are generated via a loop. Ideally I would like to do both of the following in each iteration of the loop:
generate some raw HTML output and
generate a plot.
However, I am battling to get both of these working at the same time.
If I use the following chunk options, then I get the plots but the HTML code is formatted in a "pre" environment.
```{r echo=FALSE, fig.keep = "all", fig.show = "asis"}
for (i in 1:3) {
cat("<h2>Heading</h2>")
print(ggplot(data.frame(x = 1:10, y = 1:10), aes(x = x, y = y)) + geom_point())
}
```
If I change the chunk options then I get the raw HTML but the plots disappear, being replaced by a short text snippet indicating the path to the plot.
```{r results="asis", echo=FALSE}
for (i in 1:3) {
cat("<h2>Heading</h2>")
print(ggplot(data.frame(x = 1:10, y = 1:10), aes(x = x, y = y)) + geom_point())
}
```
Is it possible to get both working at once?
This is my first attempt to do anything remotely non-trivial with Knitr, so I am sure that there is a simple answer to this question.
Best regards,
Andrew.
This seems to work at my end:
```{r results='asis', echo=F, fig.keep='all'}
for (i in 1:3) {
cat("<h2>Heading</h2>")
pl <- ggplot(data.frame(x = 1:10, y = 1:10), aes(x = x, y = y)) + geom_point()
print(pl)
}```

Resources