I want to use an otf-font in my ggplot2 graphics. I'm using Mac OS X 10.9. I found http://goo.gl/dFqJhV
But the experimental part won't work for me.
http://goo.gl/rNmIRR doesn't work either because I got lot's of errors compiling the branch. The mentioned branch seems to be too old.
The solution with cairo_pdf() (http://goo.gl/LcYFS6) does work but not for me, because I want to embed the graphics into a knitr file with output pdf and/or html.
You can try the showtext package combined with knitr using the fig.showtext=TRUE option.
Assume that the OTF font has a filename "somefont.otf", and you want to use it in R through the family name "myfont" (can be an arbitrary character string). Below is an example of an Rmd file that can be compiled into PDF or HTML:
---
output: pdf_document
---
```{r setup, include=FALSE}
library(showtext)
font.add("myfont", "somefont.otf")
```
```{r fig.showtext=TRUE, fig.width=7, fig.height=7}
plot(cars, family = "myfont")
```
Related
I want to use tikz as graphics device in RMarkdown and I want it to include the generated LaTeX preamble.
In the past, I already used tikzDevice within knitr documents. The tex file generated by tikzDevice usually included the whole preamble from my knitr/LaTeX document. When I use it with RMarkdown, I get the standard preamble (see below).
RMarkdown file:
---
title: "Title"
author: "Me"
fontsize: 12pt
documentclass: scrartcl
output:
bookdown::pdf_document2:
toc: true
fig_caption: true
keep_tex: true
---
# Introduction
```{r plot, dev="tikz"}
plot(rnorm(50))
``
Beginning of generated tex file (plot-1.tex):
% Created by tikzDevice version 0.12.3 on 2019-06-16 16:09:40
% !TEX encoding = UTF-8 Unicode
\documentclass[10pt]{article}
Desired/expected beginning of plot-1.tex:
% Created by tikzDevice version 0.12.3 on 2019-06-16 16:09:40
% !TEX encoding = UTF-8 Unicode
\documentclass[12pt]{scrartcl}
I'm not sure you really want what you're asking for. The figure will be produced as a separate document containing nothing except the figure, which will be rendered as a PDF. The differences between scrartcl and article shouldn't matter for the figure, they matter for the document as a whole.
But if you really do need that document class, you get it by specifying options(tikzDocumentDeclaration = "\\documentclass[12pt]{scrartcl}") in an R chunk early in your document. When I do that I can see in the source that it worked, but the output looks pretty much the same as it did with the default class. It's also possible to specify this using chunk options, but there's unlikely to be any advantage to doing that.
I think I figured it out:
My problem was that while using RMarkdown the options tikzDocumentDeclaration, tikzLatexPackages ... (nearly all options for tikzDevice) were not set automatically. When you use knitr the options for tikzDevice get set up in the process of splitting up markup and code chunks from the source file. With RMarkdown there is no LaTeX code to extract and use with tikz because pandoc generates it after the graphic is rendered. So one can either define the tikz... options manually or use the chunk option external=FALSE like user2554330 suggested.
Example minimal_knitr.Rnw:
\documentclass[fontsize=12pt]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\begin{document}
<<r plot, dev='tikz', echo=FALSE>>=
plot(rnorm(50))
#
\end{document}
I'm trying to knit to pdf a file with Lithuanian characters like ąčęėįšųž in RStudio from .Rmd file. While knitting to html works properly and the ggplot title has the Lithuanian characters, when knitting to pdf ggplot does create warnings and dismisses these characters.
Reproducible example:
---
title: "Untitled"
output:
pdf_document:
includes:
in_header: header_lt_text.txt
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
```
## Lithuanian char: ĄČĘĖĮŠŲŪžąčęėįšųūž
```{r}
ggplot(iris, aes(Sepal.Length, Sepal.Width))+
geom_point(aes(col=Species))+
labs(title="Lithuanian char: ĄČĘĖĮŠŲŪžąčęėįšųūž")
```
I pass the header_lt_text.txt with follwoing arguments:
\usepackage[utf8]{inputenc}
\usepackage[L7x]{fontenc}
\usepackage[lithuanian]{babel}
\usepackage{setspace}
\onehalfspacing
Any suggestions on how to make ggplot create correct labels?
The problem is with the pdf device and is only apparent when saving the picture as pdf (which you want because it looks much, much better). This is why it seems to "work" in some cases: the image is not rendered as pdf but e.g. as png. Thanks to #Konrad for correctly identifying the source of the problem.
To solve this, you need to pass the correct encoding to the pdf device.
Fortunately, the pdf device (?pdf) takes an encoding argument and there is a chunk option to pass arguments to the device: dev.args
On Windows, an appropriate encoding is CP1257.enc (Baltic):
```{r dev="pdf", dev.args=list(encoding="CP1257.enc")}
ggplot(iris, aes(Sepal.Length, Sepal.Width))+
geom_point(aes(col=Species))+
labs(title="Lithuanian char: ĄČĘĖĮŠŲŪžąčęėįšųūž")
```
You can see the other encodings available out of the box with: list.files(system.file("enc", package = "grDevices"))
Works well on my linux machine:
Alternatively, if you're happy to get png images inserted in the pdf, you can simply use dev="png" in your chunk option. Doesn't look as good though.
I'd like to include LaTeX environments (e.g., algorithmic from algorithmicx, mini from optidef, dcases from mathtools, etc.) in my .Rmd bookdown file. This is no problem for pdf output. But these do not render for html or docx output.
My current hack solution:
Generate the .pdf output.
Screen shot, edit, save images of interest as png
Include images conditional on output not being LaTeX
Downsides:
Obviously doesn't scale
Images are ugly in docx and html output
Screws with figure cross-referencing
There has to be a better approach, right? I was thinking that there's a way to tell rmarkdown/LaTeX that, when rendering as pdf, certain code chunks should be saved in some image format. That way they could be added back into the document as images conditional on the output document being docx or html. Is that even possible?
UPDATE: An answer to Standalone diagrams with TikZ suggests an approach involving the LaTeX standalone package. But unfortunately, it's discovered over at standalone does not work with algorithms that this does not work for the algorithm environment. Any ideas?
index.Rmd
---
title: "Bookdown"
header-includes:
- \usepackage{float}
- \floatplacement{figure}{!htb}
- \usepackage{algorithm}
- \usepackage{algpseudocode}
output:
bookdown::gitbook:
split_by: none
bookdown::pdf_book:
fig_caption: yes
keep_tex: yes
toc: no
bookdown::word_document2: default
site: bookdown::bookdown_site
---
```{r setup, include=FALSE, }
knitr::opts_chunk$set(echo = TRUE)
```
Hello zero
# First Chapter
Hello one
\begin{algorithm}
\caption{My Algo}
\begin{algorithmic}[1]
\State Do this.
\State Do that.
\end{algorithmic}
\end{algorithm}
```{r myalgo, echo=FALSE, eval = !knitr:::is_latex_output(), fig.cap="Must have text here. For cross-referencing to work."}
knitr::include_graphics("myalgo.png")
```
Hello two.
Check out this picture: \#ref(fig:myalgo)
myalgo.png
For math, R Markdown uses MathJax, and only a subset of LaTeX is available. This subset includes the basic math macros and environments, and allows you to define new macros, but doesn't support everything necessary to let you use arbitrary LaTeX packages. See http://docs.mathjax.org/en/latest/tex.html for details.
You might be able to create an environment that looks something like algorithm or algorithmic, but it's going to be a lot of work, and likely won't look as nice.
You should probably choose between PDF output with all of LaTeX available for formatting, or some flavour of HTML output with less style. For example, you could write your algorithm as
******
**Algorithm 1**: My algo
******
1. Do this.
2. Do that.
******
and it will display as
Algorithm 1: My algo
Do this.
Do that.
I was reading here that $$ is deprecated in LaTeX and replaced with \[ and \]. It seems the opposite when I use R Markdown in R Studio though.
If I wrap an equation in $$ it will display block style, live preview, in my R Markdown (in R Studio). If I use \[ and \] it will still knitr fine, but it won't showup R Studio live preview. See below.
---
title: "Untitled"
author: "March 2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
\[x = R + F\]
$$x = R + E$$
The linked Q&A is correct. $$ is deprecated for LaTeX. However, you are not writing LaTeX but Rmarkdown, which is processed by pandoc. In the pandoc manual we find:
TeX math will be printed in all output formats. How it is rendered depends on the output format:
LaTeX
It will appear verbatim surrounded by \(...\) (for inline math) or \[...\] (for display math).
So you can use $$...$$ in Rmarkdown documents and still have the correct output when converting to PDF via LaTeX. The other form works due to another pandoc extension. If you need cross-references for equations, you should use bookdown, though.
The following Rmarkdown renders the plotly 3D graph in HTML, but not in PDF.
Testing plotly
```{r}
library(plotly)
p <- plot_ly(data=iris, x=~Sepal.Length, y=~Sepal.Width, z=~Petal.Length,
color=~Species, symbols=c(0,1), type="scatter3d", mode="markers")
p
```
A snapshot of the graph appears as follows:
According to the plotly help page:
If you are using rmarkdown with HTML output, printing a plotly object in a code chunk will result in an interactive HTML graph. When using rmarkdown with non-HTML output, printing a plotly object will result in a png screenshot of the graph.
Is there a way to render the plotly graph in a PDF?
Note: The error from rmarkdown::render() is:
Error: Functions that produce HTML output found in document targeting latex output.
Please change the output type of this document to HTML. Alternatively, you can allow
HTML output in non-HTML formats by adding this option to the YAML front-matter of
your rmarkdown file:
always_allow_html: yes
Note however that the HTML output will not be visible in non-HTML formats.
I have created a little workaround, which saves the plotly images locally as png-file and imports it back to the RMD file.
You need the package webshot, which you can load via:
install.packages("webshot")
Further more, you need to install phantomjs via
webshot::install_phantomjs()
Then (when phantomjs is in your PATH), you can create your RMD file:
---
title: "Untitled"
output: pdf_document
---
```{r}
library(plotly)
p <- plot_ly(economics, x = ~date, y = ~unemploy / pop)
tmpFile <- tempfile(fileext = ".png")
export(p, file = tmpFile)
```
![Caption for the picture.](`r tmpFile`)
This works for me .. perhaps it's a workaround for you, too!
As #hrbrmstr commented, export() previously didn't support WebGL at all, but more recent versions support exporting to png via RSelenium (see help(export, package = "plotly")). If you need pdf export, you'll have to pay for a cloud account -- https://plot.ly/products/cloud/
Same issue with R markdown compile error:. You need to choose what format you want to KNIT to, tried to look at mine.
---
title: "<img src='www/binary-logo.jpg' width='240'>"
subtitle: "[<span style='color:blue'>binary.com</span>](https://github.com/englianhu/binary.com-interview-question) Interview Question I"
author: "[<span style='color:blue'>®γσ, Lian Hu</span>](https://englianhu.github.io/) <img src='www/ENG.jpg' width='24'> <img src='www/RYO.jpg' width='24'>白戸則道®"
date: "`r Sys.Date()`"
output:
tufte::tufte_html:
toc: yes
tufte::tufte_handout:
citation_package: natbib
latex_engine: xelatex
tufte::tufte_book:
citation_package: natbib
latex_engine: xelatex
link-citations: yes
---
What I do so that rendering to PDF's work but you can still have the interactive plots in other knit types and in rmarkdown files in r studio is:
this goes in the setup block (or really, anywhere early in the file):
is_pdf <- try (("pdf_document" %in% rmarkdown::all_output_formats(knitr::current_input())), silent=TRUE)
is_pdf <- (is_pdf == TRUE)
then this is used to render any plotly plot based on what kind of document you are creating:
if (is_pdf) { export(base_plot) } else {base_plot}
in the example base_plot is the name of the plot.