Here's a simple markdown file:
---
title: "blah"
output: html_document
---
```{r}
library(tidyverse)
ggplot(tibble(x=1:2)) +
aes(x=x, y=x) +
geom_col() +
labs(y = "← low high →")
```
Notice the arrows. They show up when running the code via the console to RStudio's plot tab. But for an HTML knit, they don't work:
Use the unicode instead of the actual character:
library(tidyverse)
ggplot(tibble(x=1:2)) +
aes(x=x, y=x) +
geom_col() +
labs(y = "\u2190 low high \u2192")
Related
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)
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:
I would like to display a single plot that takes up half of my page (to appear like it is taking up one column), using the patchwork library and the plot_spacer() function. The thing is, I can't get the "empty plot" to take up half the space! No matter what I do, the first plot seems to take up most of the page. I'm looking for the equivalent of p1 + p2 below, except I'd want p2 to be white space.
Reproducible example and output
---
title: " "
author: " "
date: " "
output: pdf_document
geometry: paperheight=8.5in,paperwidth=5.5in,left=0.4in, right=0.4in, top=0.25in, bottom=0.25in
header-includes:
- \pagenumbering{gobble}
---
{r, fig.height = 1.5}
library(ggplot2)
library(patchwork)
p1 <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point()
p2 <- ggplot() + geom_blank()
p3 <- p2 + theme_void()
p1 + plot_spacer()
p1 + p1
p1 + p2
p1 + p3
Also note that the plots appear to work in my R session but not when output to pdf:
Finally, I also tried another suggestion to use plot_layout:
design <- "
1#
"
p1 + plot_layout(design = design)
This also seems to work in the session but not in pdf_output.
If I understand you correctly, you should set out.height="50%" in your code chunk. This means that the plots will take 50% of the page. To create a white space plot, I used a theme with white background. You can see this in the code below:
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
\newpage
```{r, out.height="50%"}
library(ggplot2)
library(patchwork)
p1 <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point()
p2 <- ggplot() + geom_blank() + theme(panel.background = element_rect(fill = 'white', colour = 'white'))
p3 <- p2 + theme_void()
p1 + plot_spacer()
p1 + p1
p1 + p2
p1 + p3
```
In the pdf document you will see that the plots will plot 50% of the page. The output of p1 + plot_spacer() looks like this:
Output of p1 + p1 and p1 + p2:
And finally the output of p1 + p3:
As you can see from the images, the plots are half of the pages in a one column.
I would like to use the free font Lato in ggplot2 graphs since the remainder of my R markdown document is set in this font.
The font is installed on my system and available in the Font Book (once only).
All available fonts are loaded with the extrafont package and registered in the extrafontdb.
When I knit my markdown document as PDF, all text is correctly typeset in Lato. However, the plot labels of my ggPlots are not shown.
I also receive the following warning message:
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font width unknown for character 0x20
After embedding the fonts contained in the document with extrafont::embed_fonts the plot labels are shown for all figures using Lato as font, but
the plot labels do not contain any spaces between words,
any references (internal links, URLs, citations) do not work anymore.
An MWE including ggPlot figures with and without Lato as the font is provided below (Lato is freely available here)
To embed the fonts afterwards one needs to run embed_fonts("TestRmd.pdf", outfile="TestRmd_embedded.pdf")
Any help is greatly appreciated!
MWE:
---
title: "Embedding Fonts in PDF"
output: pdf_document
urlcolor: blue
---
```{r echo=FALSE}
library(ggplot2)
```
### Plot with standard font {#standard}
```{r echo=FALSE, out.width = '30%'}
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon")
```
### Load fonts and set font for ggplots globally
```{r include=FALSE}
# install.packages("extrafont") # see https://github.com/wch/extrafont/
library(extrafont)
# font_import() # run once
loadfonts() # loadfonts
# globally set ggplot2 theme and font ("Lato Light")
theme_set(theme_minimal(base_size=12, base_family="Lato Light"))
```
### Plot with newly set standard font (= Lato) {#lato}
```{r echo=FALSE, out.width = '30%'}
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon")
```
### Plot with Impact font {#impact}
```{r echo=FALSE, out.width = '30%'}
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme(text=element_text(size=16, family="Impact"))
```
### Run to embed fonts
```{r eval=FALSE, include=TRUE}
embed_fonts("TestRmd.pdf", outfile="TestRmd_embedded.pdf")
```
### Links test
Links test 1 (internal reference): [Headline standard](#standard)
Links test 2 (URL): [RStudio has become a Public Benefit Corporation](https://blog.rstudio.com/2020/01/29/rstudio-pbc)
AddOn:
An even simpler problem but likely related to the same issue:
library(extrafont)
extrafont::font_import()
p <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + theme_minimal(base_size=10, base_family="Lato Light")
ggsave(p, filename = "iris.pdf")
The plot in the saved pdf does not contain any labels. Using cairo_pdf as recommend on several SO (e.g. 1, 2) sites does not help and results in the following error:
ggsave(p, filename = "iris.pdf", device = cairo_pdf)
# In dev(filename = filename, width = dim[1], height = dim[2], ...) :
# failed to load cairo DLL
I tried to make it work using extrafont but did not succeed. I am still not quite sure but I think it is a bug. Here is a solution using the package showtext:
---
title: "Embedding Fonts in PDF"
output: pdf_document
urlcolor: blue
---
```{r include=FALSE}
# notice the chunk option 'fig.showtext' that tells R to use the showtext
# functionalities for each ne graphics device opened
knitr::opts_chunk$set(dev = 'pdf', cache = FALSE, fig.showtext = TRUE)
library(ggplot2)
library(showtext)
font_add(family = "Lato", regular = "/Users/martin/Library/Fonts/Lato-Light.ttf")
```
### Plot with newly set standard font (= Lato) {#lato}
```{r echo=FALSE, out.width = '100%'}
ggplot(mtcars, aes(x=wt, y=mpg)) +
geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") +
ylab("Miles per Gallon") +
theme(text = element_text(family="Lato"))
```
---
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: