Using tikz graphdrawing library within RMarkdown ... Need to use lualatex engine, but can't get it to work - knitr

I have the following code in an rmd file which leverages tikz for diagrams:
---
title: "TestNonTufteLua"
author: "Me"
output:
pdf_document :
latex_engine: lualatex
---
Prove tikz works:
```{r tikTest1, engine = "tikz"}
\usetikzlibrary{shapes}
\begin{tikzpicture}
\node[ellipse, draw=black, align = center] (Data) {Data $y_{n}$};
\end{tikzpicture}
```
Then, when you set `eval = TRUE` in the below code, it will not work.
```{r tikTest2, eval = FALSE, engine = "tikz"}
\usetikzlibrary{graphs, graphdrawing}
\usegdlibrary{layered}
\tikz [gr/.style={gray!50}, font=\bfseries]
\graph [layered layout] {
% A and F are horizontally aligned if you also set weight=0.5 for A -- C.
A -- [minimum layers=2] C -- F,
{ [nodes=gr, edges=gr] A -- B -- { E, D -- F } }
};
```
When changing to eval=TRUE in the second chunk, I get the following
error:
Quitting from lines 24-29 (testNonTufteLua.Rmd) Error: running
'texi2dvi' on '.\tikz36747a021b22.tex' failed
LaTeX errors: rarygraphdrawing.code.tex:22: Package pgf Error: You
need to run LuaTeX to use the graph drawing library.
This error occurs when using the knit button from RStudio or using render("testNonTufteLua.Rmd", output_format = pdf_document(keep_tex = TRUE, latex_engine = "lualatex"). I have also experimented with setting options(tikzDefaultEngine = "luatex") to get tikzDevice to handle it properly, but it still does not work. I just can't seem to get the graphdrawing library to work even though the tikz-shapes library can be loaded and also that the rest of the document seems to be compiled with lualatex. Thanks for any help!!

Update: Meanwhile knitr no longer uses tools::texi2dvi but tinytex::latexmk. One therefore has to use options(tinytex.engine = 'lualatex') in a set-up chunk.
This is rather tricky, since you are not using tikzDevice but the tikz engine, which uses tools::texi2dvi to convert to PDF. You can change this using options(texi2dvi = "lualatex"). However, the default template does not work with LuaLaTeX. I have therefore created a modified template:
\RequirePackage{luatex85}
\documentclass{article}
\usepackage[luatex,active,tightpage]{preview}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{preview}
%% TIKZ_CODE %%
\end{preview}
\end{document}
And specify that file with engine.opts = list(template = "tikz2pdf.tex"). Putting it all together here my working file:
---
title: "TestNonTufteLua"
author: "Me"
output:
pdf_document :
latex_engine: lualatex
---
```{r}
options(texi2dvi = "lualatex")
```
```{r tikTest2, eval = TRUE, engine = "tikz", engine.opts = list(template = "tikz2pdf.tex")}
\usetikzlibrary{graphs, graphdrawing}
\usegdlibrary{layered}
\tikz [gr/.style={gray!50}, font=\bfseries]
\graph [layered layout] {
% A and F are horizontally aligned if you also set weight=0.5 for A -- C.
A -- [minimum layers=2] C -- F,
{ [nodes=gr, edges=gr] A -- B -- { E, D -- F } }
};
```
Result:
References:
how to set engine options
preview and LuaLaTeX
knitr using texi2pdf

A small running variation of the example above is the following using tinytex.
---
title: "lualatex. Using `tinytex.engine`"
output:
html_document:
df_print: paged
pdf_document:
latex_engine: lualatex
---
## Latex engines
By default, PDF documents are rendered using `pdflatex`. You can specify an
alternate engine using the `latex_engine` option. Available engines
are `pdflatex`, `xelatex`, and `lualatex.`
```{r setup}
options(tinytex.engine = "lualatex")
```
```{r tikzLua, eval = TRUE, engine = "tikz", engine.opts = list(template = "tikz2pdf.tex")}
\usetikzlibrary{graphs, graphdrawing}
\usegdlibrary{layered}
\tikz [gr/.style={gray!50}, font=\bfseries]
\graph [layered layout] {
% A and F are horizontally aligned if you also set weight=0.5 for A -- C.
A -- [minimum layers=2] C -- F,
{ [nodes=gr, edges=gr] A -- B -- { E, D -- F } }
};
```
After an update in knitr the example above stopped running.

Related

abnormal behaviour of neovim with lsp clangd

this is my code that print hello world
now if i use command Format that call vim.cmd [[ command! Format execute 'lua vim.lsp.buf.formatting()' ]]
my code will becames like this now strange symbols appear in the text
clangd changes my text with ^M symbol
neovim version:0.6.1
this is a part of my lsp-installer configuration file:
lsp_installer.on_server_ready(function(server)
local opts = {
on_attach = require("config.lsp.handlers").on_attach,
capabilities = require("config.lsp.handlers").capabilities,
}
-- Lua
if server.name == "sumneko_lua" then
local sumneko_opts = require("config.lsp.settings.sumneko_lua")
opts = vim.tbl_deep_extend("force", sumneko_opts, opts)
end
-- Python
if server.name == "pyright" then
local pyright_opts = require("config.lsp.settings.pyright")
opts = vim.tbl_deep_extend("force", pyright_opts, opts)
end
-- C/C++
-- if server.name == "clangd" then
--
-- end
-- This setup() function is exactly the same as lspconfig's setup function.
-- Refer to https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md
server:setup(opts)
end)

How to include a png file in R flexdashboard

Could you please help me in finding the right code to print a png image inside a R flexdashboard?
Here my code chunk:
---
title: "Analyse des installations PV - Les Vergers"
author: "Dario Santandrea"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
flexdashboard::flex_dashboard:
orientation: rows
vertical_layout: fill
runtime: shiny
---
First attempt
renderImage({
outfile <- tempfile(fileext = "X:/LesVergers/Analyse/BilanSolaire/Figures/Solar_angle_scheme.png")
png(outfile, width = 500, height = 400)
dev.off()
}
)
Second attempt
#knitr::include_graphics("X:/LesVergers/Analyse/BilanSolaire/Figures/Solar_angle_scheme.png")
The image i've been trying to print doesn't simply appear in the flexdashboard
flexdashboard is essentially Markdown. Thus see e.g. this related thread.
```{r picture, echo = F, fig.cap = "Title", out.width = '100%'}
knitr::include_graphics("picture.png")
```
Just place this chunk within the standard flexdashboard layout:
BLOCK1
=====================================
Row {data-width=1000}
-----------------------------------------------------------------------
### A picture
```{r picture, echo = F, fig.cap = "Title", out.width = '100%'}
knitr::include_graphics("picture.png")
```

How to use different "dev.off()" with knitr (to auto-crop figures)

I would like to use my own pdf() plot device in an .Rnw document converted to a PDF with knitr. After the PDF of a figure is generated
it should call pdfCrop.off() instead of dev.off() (or whatever knitr calls); this would
perfectly crop the resulting figures. How can this be done?
The following MWE works (but without cropping) if (*) is commented out (and the line before properly closed).
\documentclass{article}
\begin{document}
<<knitr_options, echo = FALSE, results = "hide", purl = FALSE>>=
## Custom graphics device (for cropping .pdf):
pdfCrop <- function(file, width, height, ...)
{
f <- file
grDevices::pdf(f, width = width, height = height, onefile = FALSE)
assign(".pdfCrop.file", f, envir = globalenv())
}
pdfCrop.off <- function() # used automagically
{
grDevices::dev.off() # closing the pdf device
f <- get(".pdfCrop.file", envir = globalenv())
system(paste("pdfcrop --pdftexcmd pdftex", f, f, "1>/dev/null 2>&1"),
intern = FALSE) # crop the file (relies on PATH)
}
## knitr options
knitr::opts_chunk$set(fig.path = "./fig_", background = "#FFFFFF",
dev = "pdfCrop", fig.ext = "pdf") # (*) => how to use pdfCrop.off() instead of dev.off()?
#
<<MWE>>=
<<fig-MWE, eval = FALSE, echo = FALSE>>=
plot(1:10, 10:1)
#
\setkeys{Gin}{width=\textwidth}
\begin{figure}[htbp]
\centering
\framebox{
<<figMWE, echo = FALSE, fig.width=6, fig.height=6>>=
<<fig-MWE>>
#
}
\caption{Just some text to show the actual textwidth in order to see that the
figure is not perfectly horizontally aligned due to some white space which can
be avoided by properly crop the figure with an adequate pdf crop device.}
\end{figure}
\end{document}
knitr already provides a crop device based on pdfcrop, so we can use that via a hook:
\documentclass{article}
\begin{document}
<<knitr_options, echo = FALSE, results = "hide", purl = FALSE>>=
## knitr options
library(knitr)
knit_hooks$set(crop = hook_pdfcrop)
knitr::opts_chunk$set(fig.path = "./fig_", # all figures are saved as fig_*
background = "#FFFFFF", # avoid color
crop = TRUE) # always crop
#
<<MWE>>=
<<fig-MWE, eval = FALSE, echo = FALSE>>=
plot(1:10, 10:1)
#
\setkeys{Gin}{width=\textwidth}
\begin{figure}[htbp]
\centering
<<figMWE, echo = FALSE, fig.width=6, fig.height=6>>=
<<fig-MWE>>
#
\caption{Just some text to show the actual textwidth in order to see that the
figure is not perfectly horizontally aligned due to some white space which can
be avoided by properly crop the figure with an adequate pdf crop device.}
\end{figure}
\end{document}

Why does my R notebook produce a blank html document

For some reason, my R notebook is producing a blank HTML document. When I'm ready to knit the document to an html notebook, my browser opens up the file and it is a blank document. I'm pressing the "knit" button, then "html" from R Studio.
Here is my code:
---
title: "Rate Hole Model"
output: html_document
---
```{r}
library(tidyverse)
library(plotly)
library(rmarkdown)
library(knitr)
```
```{r}
veh_age <- mc2 %>%
filter(cummulative < 51)
plot_ly(veh_age, x = ~unit_age, y = ~loss_ratio, color = ~rating_class_name) %>%
add_markers(text = ~paste(rating_class_name, "<br />", 'unit age: ',
unit_age, "<br />", 'loss ratio: ', loss_ratio), hoverinfo =
'text') %>%
layout(title = 'Comp Loss Ratio by Unit Age/Rating Class')
```
I'm not sure what happened. I'm on R version 3.5.1Has anyone ran into this problem?
My Libraries were installed to my Home directory : \Home\firstname.lastname\documents. This directory is a network located resource. When the last step of the process ran, the proper permission was not available to the called application (Pandoc). I am running 64 bit Win 10 with 64 bit RStudio version 1.1.456 and the 3.5 version of R. When I moved (reinstalled) the packages/libraries to a local folder : c:\Program Files\RStudio\Packages the HTML rendered in the browser.

Aligning and italicising table column headings using Rmarkdown and pander

I am writing a rmarkdown document knitting to pdf with tables taken from portions of lists from the ezANOVA package. The tables are made using the pander package. Toy Rmarkdown file with toy dataset below.
---
title: "Table Doc"
output: pdf_document
---
```{r global_options, include=FALSE}
#set global knit options parameters.
knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.path='Figs/',
echo=FALSE, warning=FALSE, message=FALSE, dev = 'pdf')
```
```{r, echo=FALSE}
# toy data
id <- rep(c(1,2,3,4), 5)
group1 <- factor(rep(c("A", "B"), 10))
group2 <- factor(rep(c("A", "B"), each = 10))
dv <- runif(20, min = 0, max = 10)
df <- data.frame(id, group1, group2, dv)
```
``` {r anova, echo = FALSE}
library(ez)
library(plyr)
library(pander)
# create anova object
anOb <- ezANOVA(df,
dv = dv,
wid = id,
between = c(group1, group2),
type = 3,
detailed = TRUE)
# extract the output table from the anova object, reduce it down to only desired columns
anOb <- data.frame(anOb[[1]][, c("Effect", "F", "p", "p<.05")])
# format entries in columns
anOb[,2] <- format( round (anOb[,2], digits = 1), nsmall = 1)
anOb[,3] <- format( round (anOb[,3], digits = 4), nsmall = 1)
pander(anOb, justify = c("left", "center", "center", "right"))
```
Now I have a few problems
a) For the last three columns I would like to have the column heading in the table aligned in the center, but the actual column entries underneath those headings aligned to the right.
b) I would like to have the column headings 'F' and 'p' in italics and the 'p' in the 'p<.05' column in italics also but the rest in normal font. So they read F, p and p<.05
I tried renaming the column headings using plyr::rename like so
anOb <- rename(anOb, c("F" = "italic(F)", "p" = "italic(p)", "p<.05" = ""))
But it didn't work
In markdown, you have to use the markdown syntax for italics, which is wrapping text between a star or underscore:
> names(anOb) <- c('Effect', '*F*', '*p*', '*p<.05*')
> pander(anOb)
-----------------------------------------
Effect *F* *p* *p<.05*
--------------- ------ -------- ---------
(Intercept) 52.3 0.0019 *
group1 1.3 0.3180
group2 2.0 0.2261
group1:group2 3.7 0.1273
-----------------------------------------
If you want to do that in a programmatic way, you can also use the pandoc.emphasis helper function to add the starts to a string.
But your other problem is due to a bug in the package, for which I've just proposed a fix on GH. Please feel free to give a try to that branch and report back on GH -- I will try to get some time later this week to clean up the related unit tests and merge the branch if everything seem to be OK.