---
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:
Related
The plot below was generated in R (without any issue), using this code:
library(tidyverse)
library(extrafont)
loadfonts()
x <- rexp(100)
data.frame(info = x) %>%
ggplot() +
geom_histogram(aes(x = info), col = "red", fill = "red", alpha = 0.5) +
theme_minimal() +
theme(text = element_text(family="LM Roman 10"))
As you can see, the font of the plot is set to "LM Roman 10", which I was able to do thanks to this post and it works perfectly within R.
However when I try to place the image in a LaTeX document using RMarkdown, I get this error:
Quitting from lines 10-22 (min_example.Rmd)
Error in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
invalid font type
Calls: <Anonymous> ... drawDetails -> drawDetails.text -> grid.Call.graphics
Además: There were 50 or more warnings (use warnings() to see the first 50)
Ejecución interrumpida
Here is the code for min_example.Rmd
---
title: "Untitled"
author: "Javier Rojas"
date: "2/9/2020"
output: pdf_document
---
```{r, echo=FALSE}
library(tidyverse)
library(extrafont)
loadfonts()
x <- rexp(100)
data.frame(info = x) %>%
ggplot() +
geom_histogram(aes(x = info), col = "red", fill = "red", alpha = 0.5) +
theme_minimal() +
theme(text = element_text(family="LM Roman 10"))
```
I am using a Mac computer running macOS High Sierra and R 3.6.1
Usually quite easy to solve. The problem should be, that the font is not installed in your computer.
You have to download the .otf file for the font e.g. (https://fonts2u.com/lmroman10-regular.font) and install it on your Operating System.
If you don't know how to do this, just google it (e.g. "install extra font Windows"), there are plenty of tutorials on it online.
-edit-
I was a little to quick - didn't realize the problem just comes from running it in rmarkdown. Try the following:
```{r, fig.showtext=TRUE, echo=FALSE}
library("tidyverse")
library("showtext")
x <- rexp(100)
font_add("LM Roman 10", regular = "lmroman10-regular.otf")
data.frame(info = x) %>%
ggplot() +
geom_histogram(aes(x = info), col = "red", fill = "red", alpha = 0.5) +
theme_minimal() +
theme(text = element_text(family="LM Roman 10"))
```
It's important that you add fig.showtext=TRUE, library("showtext") and font_add("LM Roman 10", regular = "lmroman10-regular.otf").
I just placed the .otf in my project folder - but I think you can also give it another path.
There exists a current new approach using showtext and showtextdb packages.
On Windows, install manually Latin Modern Roman font (.tff version) following these steps easy instructions https://tex.stackexchange.com/questions/55787/latin-modern-roman-for-ttf. After the installation, you can locate all your fonts in "C:/Windows/Fonts/" just in case.
Once it's already installed, try the following R code to see and example:
install.packages("showtext")
install.packages("showtextdb")
library(showtext)
library(showtextdb)
#set the name and file path
font_add(family = "lmroman10", regular = "C:/Windows/Fonts/lmroman10-regular-webfont.ttf")
showtext_auto()
library(ggplot2)
p = ggplot(NULL, aes(x = 1, y = 1)) + ylim(0.8, 1.2) +
theme(axis.title = element_blank(), axis.ticks = element_blank(),
axis.text = element_blank()) +
annotate("text", 1, 1.1, family = "lmroman10", size = 15,
label = "Text using new font")
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")
When knitting a simple bar chart to pdf, I get some unwanted stripes in my bars (see right side of the attached screenshot).
---
title: "Don't Panic"
author: "Ford Perfect"
output: pdf_document
---
```{r, include = F}
library(ggplot2)
```
# Introduction
```{r, echo = F, fig.cap = "My plot"}
ggplot(mpg) + geom_bar(aes(x = as.factor(cyl), y = hwy), stat="identity")
```
These stripes do not appear when I create the plot directly in R-Studio (see left side of the attached screenshot).
I found a way to remove these stripes by aggregating the data before:
ggplot(aggregate(hwy~cyl,mpg,"sum")) +
geom_bar(aes(x = as.factor(cyl), y = hwy), stat="identity")
So I understand that these stripes should be coming from stacking all the other groups in the datasets. This theory seems plausible, since I get two stripes when I aggregate the dataset also by years (2 uniques in mpg dataset).
ggplot(aggregate(hwy~cyl*year,mpg,"sum")) +
geom_bar(aes(x = as.factor(cyl), y = hwy), stat="identity")
But I thought that ggplot2 is automatically doing the aggregation for me when I set stat to identity? Actually it does work directly in R-Studio. So maybe the problem has more to do with knitr?
I do believe that I did not had this same issue in the past. So maybe something changed with an update? Actually all my colleagues (6 other mac and windows computers) have the exact same problem.
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
ggplot2: 2.2.1
knitr: 1.15.1
As noted in a comment, the file type for the graphic can influence the way the graphic renders in the output pdf.
Using the provided chunk:
```{r, echo = F, fig.cap = "My plot"}
ggplot(mpg) + geom_bar(aes(x = as.factor(cyl), y = hwy), stat="identity")
```
The default dev is pdf and the resulting graphic in the pdf is as shown in the question post:
If you are explicit on the dev to use, as in the chunk below, then a png will be generated and the image in the resulting pdf is as wanted.
```{r, echo = F, fig.cap = "My plot", dev = "png"}
ggplot(mpg) + geom_bar(aes(x = as.factor(cyl), y = hwy), stat="identity")
```
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}
Here's my code that's supposed to display to graphics next to each other, but fails to do so. In fact the sweave part is not interpreted.
\begin{figure}[h]
\begin{center}
\begin{minipage}[t]{.485\linewidth} %
<<fig=true,echo=false>>=
print(graph2)
#
\newline{\color{red}{\caption{\label{idx}Graph one}}}
\end{minipage}
\hspace{.02\linewidth}
\begin{minipage}[t]{.485\linewidth}%
<<fig=true,echo=false>>=
print(graph2)
#
\newline{\color{red}{ \caption{\label{pb}Graph two}}}
\end{minipage}
\end{center}
\end{figure}
graph1,graph2 is just any given graph created by qplot. Both graphs work just fine outside a minipage. I know this topic has been around, but somehow I could not get solutions to got that worked for others like this one.
Plus I have a little side question: What's the argument to prevent Sweave from generating both .eps and .pdf ? The manual just states that it is the default. However I am sure that I just use pdflatex and hence do not need .eps.
Eh, this is actually cheating, but a found a nice workaround on John's blog. It's not using minipage but it's getting it done by using subfigure. Subfigure did not have any problems with Sweave. Nice!
If you are interested in this solution check this site. Still i´d like to know how to do it with minipage :)
Replacing \hspace with \hfill does the trick. The plots are from the ggplot documentation. minipage also works nicely for putting two xtable side by side, or a table and a plot.
\documentclass{article}
\usepackage{color}
\begin{document}
\begin{figure}[h]
\begin{center}
\begin{minipage}[t]{.49\linewidth} %
<<fig=true,echo=false>>=
require(ggplot2)
df <- data.frame(gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30))
library(plyr)
ds <- ddply(df, .(gp), summarise, mean = mean(y), sd = sd(y))
ggplot(df, aes(x = gp, y = y)) +
geom_point() +
geom_point(data = ds, aes(y = mean),colour = 'red', size = 3)
#
\newline{\color{red}{\caption{\label{idx}Graph one}}}
\end{minipage}
\hfill
\begin{minipage}[t]{.49\linewidth}
<<fig=true,echo=false>>=
ggplot() +
geom_point(data = df, aes(x = gp, y = y)) +
geom_point(data = ds, aes(x = gp, y = mean),
colour = 'red', size = 3) +
geom_errorbar(data = ds, aes(x = gp, y = mean,
ymin = mean - sd, ymax = mean + sd),
colour = 'red', width = 0.4)
#
\newline{\color{red}{ \caption{\label{pb}Graph two}}}
\end{minipage}
\end{center}
\end{figure}
\end{document}