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")
```
Related
I am having difficulty getting LaTeX math expressions to properly render when using knitr and kableExtra to compile a table in a Beamer presentation. I was originally use xelatex as my engine, and then switched to pdflatex to see if this would resolve the issue. I'm stumped on this one.
TeX preamble
% For resizing caption font size
\usepackage{caption}
\captionsetup[figure]{font=tiny}
% Other packages
\usepackage{fancyvrb}
\usepackage{color,xcolor}
\usepackage{framed}
\usepackage{booktabs}
\usepackage{longtable}
\usepackage{array}
\usepackage{multirow}
\usepackage{wrapfig}
\usepackage{float}
\usepackage{colortbl}
\usepackage{pdflscape}
\usepackage{tabu}
\usepackage{threeparttable}
\usepackage{threeparttablex}
\usepackage[normalem]{ulem}
\usepackage{makecell}
% Colour formatting
\definecolor{UBCblue}{rgb}{0.04706, 0.13725, 0.26667} % UBC Blue (primary)
\definecolor{UBCgrey}{rgb}{0.3686, 0.5255, 0.6235} % UBC Grey (secondary)
\setbeamercolor{title}{fg=UBCblue} % slide title
\setbeamercolor{frametitle}{fg=UBCblue} % slide title
\setbeamercolor{structure}{fg=darkgray} % more list stuff, I think
\setbeamertemplate{itemize items}[circle] % for list itemes
% Page numbers
\setbeamertemplate{navigation symbols}{}
\setbeamertemplate{footline}[page number]
% Margins
\setbeamersize{text margin left=8mm,text margin right=8mm}
% make code-output smaller
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{fontsize=\footnotesize,commandchars=\\\{\}}
% make console-output smaller:
\makeatletter
\def\verbatim{\footnotesize\#verbatim \frenchspacing\#vobeyspaces \#xverbatim}
\makeatother
\setlength{\parskip}{0pt}
\setlength{\OuterFrameSep}{-4pt}
\makeatletter
\preto{\#verbatim}{\topsep=-10pt \partopsep=-10pt }
\makeatother
% For better spacing between the list bullets
\renewcommand{\tightlist}{\setlength{\itemsep}{1ex}\setlength{\parskip}{0pt}}
RMarkdown Document
---
title: "My Title"
subtitle: "My Subtitle"
author: Speleo4Life
date: "March 11th, 2021"
output:
beamer_presentation:
latex_engine: pdflatex
includes:
in_header: preamble.tex
theme: "default"
colortheme: "orchid"
fonttheme: "serif"
slide_level: 2
keep_tex: true
urlcolor: blue
linkcolor: purple
---
```{r setup, eval=TRUE, include=FALSE, echo=FALSE}
library(tidyverse)
library(ggplot2)
library(kableExtra)
library(psych)
```
```{r, eval=TRUE, echo=FALSE}
knitr::opts_chunk$set(echo = TRUE)
options(knitr.table.format = "latex")
```
## Review: Null Hypothesis Significance Testing
```{r, echo=FALSE}
c1 <- c('$\\text{Reject } H_0$', '$\\text{Retain } H_0$')
c2 <- c('$\\text{Type I Error } (\\alpha)$', 'Correct Retention')
c3 <- c('$\\text{Power } (1-\\beta)$', '$\\text{Type II Error } \\beta$')
df <- data.frame(c1,c2,c3)
colnames(df) <- c('$\\textbf{Decision}$', '$\\mathbf{H_0} \\textbf{\\textit{is true}}$',
'$\\mathbf{H_0} \\textbf{\\textit{is false}}$')
kbl(df, booktabs = T) %>%
add_header_above(c(" ", "State of Reality" = 2))
```
Relevant Output
Just add escape = F to kbl:
---
title: "My Title"
subtitle: "My Subtitle"
author: Speleo4Life
date: "March 11th, 2021"
output:
beamer_presentation:
latex_engine: pdflatex
includes:
in_header: preamble.tex
theme: "default"
colortheme: "orchid"
fonttheme: "serif"
slide_level: 2
keep_tex: true
urlcolor: blue
linkcolor: purple
---
```{r setup, eval=TRUE, include=FALSE, echo=FALSE}
library(tidyverse)
library(ggplot2)
library(kableExtra)
library(psych)
```
```{r, eval=TRUE, echo=FALSE}
knitr::opts_chunk$set(echo = TRUE)
options(knitr.table.format = "latex")
```
## Review: Null Hypothesis Significance Testing
```{r, echo=FALSE}
c1 <- c('$\\text{Reject } H_0$', '$\\text{Retain } H_0$')
c2 <- c('$\\text{Type I Error } (\\alpha)$', 'Correct Retention')
c3 <- c('$\\text{Power } (1-\\beta)$', '$\\text{Type II Error } \\beta$')
df <- data.frame(c1,c2,c3)
colnames(df) <- c('$\\textbf{Decision}$', '$\\mathbf{H_0} \\textbf{\\textit{is true}}$',
'$\\mathbf{H_0} \\textbf{\\textit{is false}}$')
kbl(df, booktabs = T, escape = F) %>%
add_header_above(c(" ", "State of Reality" = 2))
```
-output
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}
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.
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.
I want to include a gnuplot code inside a markdown page and have Jekyll compile the graph when I save it. The graph image is being saved. But it is removed during jekyll's cleanup. The closest that I have found toward a solution is at Copying generated files from a Jekyll plugin to a site resource folder. However, I don't undersand the overall flow of Jekyll and how I keep static files from being removed. I have added site.static_files << Jekyll::StaticFile.new(site, site.source, path, filename) with no results.
If I create a dummy file outside of the _site folder, Jekyll will keep my file safe inside the _site file. I would rather not have to create that dummy file.
Here is code for my plugin. Any help will be awesome.
class RenderGNUplot < Liquid::Block
def initialize(tag_name, markup, tokens)
super
#markup = markup
#attributes = {}
markup.scan(Liquid::TagAttributes) do |key, value| #attributes[key.to_sym] = value end
end
def gnuplot(commands)
IO.popen("gnuplot", "w") { |io| io.puts commands }
end
def render(context)
site = context.registers[:site]
#file = ""
commands = super
if ( commands =~ /set output "(.*)"/ )
setfile_regex = Regexp.new(/set output "((.*))"/)
filepath = commands[setfile_regex, 1]
#file = File.basename filepath
commands = commands.sub!(commands[setfile_regex], 'set output "_site/media/' + #file +'"' )
p commands
end
gnuplot(commands)
site.static_files << Jekyll::StaticFile.new(site, site.source, "_site/media/", "#{#file}")
# site.static_files << Jekyll::StaticSitemapFile.new(site, site.dest, '/', 'sitemap.xml')
"<object id='' type='image/svg+xml' data='#{site.baseurl}/media/{#file}'>Your browser does not support SVG</object>"
end
end
Liquid::Template.register_tag('test', RenderGNUplot)
And Markdown page
---
layout: post
title: "Thin Server"
date: 2015-04-28 10:42:56
categories: thin
---
{% test location: Test%}
set terminal svg size 600,400 dynamic enhanced fname 'arial' fsize 10 #mousing jsdir 'http://localhost:4000/media/' name "histograms_1" butt dashlength 1.0
set output "media/curves.svg"
set key inside left top vertical Right noreverse enhanced autotitle box lt black linewidth 1.000 dashtype solid
set samples 50, 50
set title "Simple Plots"
set title font ",20" norotate
plot [-10:10] sin(x),atan(x),cos(atan(x))
{% endtest%}
This is the exact code that I am using. It only has the Liquid block and jekyll StaticFile
class GNUplotFile < Jekyll::StaticFile
def write(dest)
puts "WRITE---->>>>>>>>>>>"
#File.write('_site/media/BTTTTT.svg', DateTime.now)
gnuplot(#commands)
# do nothing
end
def gnuplot(commands)
IO.popen("gnuplot", "w") { |io| io.puts commands }
end
def givemethecommands(commands)
#commands = commands
end
end
class RenderGNUplot < Liquid::Block
def initialize(tag_name, markup, tokens)
super
#markup = markup
#attributes = {}
markup.scan(Liquid::TagAttributes) do |key, value| #attributes[key.to_sym] = value end
end
def render(context)
site = context.registers[:site]
#file = ""
commands = super
if ( commands =~ /set output "(.*)"/ )
setfile_regex = Regexp.new(/set output "((.*))"/)
filepath = commands[setfile_regex, 1]
#file = File.basename filepath
commands = commands.sub!(commands[setfile_regex], 'set output "_site/media/' + #file +'"' )
#p commands
end
gnuplot = GNUplotFile.new(site, site.source, "_site/media/", "#{#file}")
gnuplot.givemethecommands commands
site.static_files << gnuplot
# site.static_files << Jekyll::StaticFile.new(site, site.dest, '/', 'sitemap.xml')
"<object id='' type='image/svg+xml' data='#{site.baseurl}/media/#{#file}'>Your browser does not support SVG</object>"
end
end
Liquid::Template.register_tag('test', RenderGNUplot)