I would like to use non-standard fonts in a ggplot2 chart which I then embed in an rmarkdown document, which get knitted into a PDF. My current workflow is to specify the font in the chart, then knit, then run extrafonts::embed_fonts on the created PDF. My question is: can I specify directly in the rmarkdown document that fonts should be embedded in the outputted PDF?
Minimal example:
---
title: "Untitled"
output: beamer_presentation
---
```{r}
library(extrafont)
library(ggplot2)
loadfonts()
qplot(iris$Sepal.Length) + theme_light(base_family = "CM Roman")
```
knitr::knit2pdf("test.rmd")
embed_fonts("test.pdf")
If you set the graphics device to "cairo_pdf" the fonts will be embedded. You can do this for individual chunks or for the whole document using knitr::opts_chunk$set
I used a really obviously different font below so that it was clear the fonts were really being set.
The package is called "extrafont" not "extrafonts"
---
title: "Untitled"
output: beamer_presentation
---
```{r, echo=FALSE, message = FALSE}
knitr::opts_chunk$set(warning=FALSE, message=FALSE, echo = FALSE, dev = "cairo_pdf")
```
```{r}
library(extrafont)
library(ggplot2)
loadfonts()
```
##
```{r, fig.width = 5}
qplot(iris$Sepal.Length) + theme_light(base_family = "Vladimir Script")
```
Related
This is a follow-up question about this answer. I have set the knitr chunk options to output a png and pdf version of plots in a folder, as well as use the pngs in the knitted report.
However, I'd only like to keep the pdf version of the figure and discard the png file. Is there a knitr-equivalent of on.exit() to clean up the pngs after knitting? Or an option I overlooked?
With the rmarkdown document below, how do I automatically clean up the png version of the plot after knitting? (Or not produce it as a standalone file in the first place)
---
title: "Untitled"
author: "Me"
date: "21/10/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
dev = c("png", "pdf"),
fig.path = here::here(
"figures",
gsub("\\.Rmd$", "\\\\", basename(knitr::current_input()))
)
)
```
```{r my_plot}
library(ggplot2)
ggplot(mpg, aes(displ, hwy)) +
geom_point()
```
That is not exactly what you are looking for, but manually removing eval=FALSE from the following chunk, deletes the wanted files:
```{r eval=FALSE, include=FALSE}
fList <- dir("figures")
fList <- fList[stringr::str_detect(fList,"\\.png$")]
file.remove(paste0("figures/",fList))
```
I am attempting to use R Markdown Notebooks (.Rmd files) in R Studio to capture notes and excercises while learning R programming. I find that any plots generated through the code chunks are being replicated in the corresponding html file correctly, however I am unable to get images to be replicated in the html.
Sample code below -
The image is a .PNG file in the working directory path.
```{r}
library(knitr)
knitr::include_graphics("MyImage.PNG")
```
This replicates the image in the R Markdown Notebook correctly, but not in the html file.
I am able to replicate the image in the html file by directly using html syntax -
<img src="MyImage.PNG" alt="MyImage">
I have looked through other questions around this topic, but could not resolve this issue through any of the solutions provided. I would be grateful if any of you can help resolve this.
Thanks!
I think this might be a bug to do with adding shiny.
I just did a quick test and it works for a normal document:
---
title: "Test"
output: html_document
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(echo = TRUE)
```
```{r, echo=FALSE, out.width="50%"}
include_graphics("../images/RMarkdownOutputFormats.png")
```
but when I add shiny it doesn't work anymore:
---
title: "Test"
output: html_document
runtime: shiny
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(echo = TRUE)
```
```{r, echo=FALSE, out.width="50%"}
include_graphics("../images/RMarkdownOutputFormats.png")
```
I had the same problem when using shiny_prerendered with a learnr tutorial... This from Yan Holtz worked for me:
library(png)
library(grid)
img <- readPNG("photos/header_stats.png")
grid.raster(img)
I'm trying to get the PNG plots from knitr output to write to disk as separate files without doing it manually.
What I tried
The dev = 'png' setting from http://gforge.se/2014/01/fast-track-publishing-using-knitr-part-iii/ (also mentioned in this question)
self_contained: no from knitr: include figures in report *and* output figures to separate files.
Neither worked. The folder the knitting process ran in has no extra files, and the HTML document has base64 embedded images in its source.
Environment
RStudio 0.99.903
R 3.2.3
knitr 1.15.1
MWE: The RStudio RMarkdown file, with abovementioned options added:
---
title: "Untitled"
output: html_document
self_contained: no
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(dev="png",
dev.args=list(type="cairo"),
dpi=96)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
self_contained is an option for html_document, not a top-level YAML setting. The document below works using just that. PNG is the default figure type, so you don't need to specify that.
---
title: "Untitled"
output:
html_document:
self_contained: no
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Jallen produced a solution for producing knitr plots, labels, and captions within one chunk - for Rnw files.
knitr plots, labels, and captions within one chunk
This works nicely for .Rnw but I can't make it work for .Rmd, don't see what is going wrong...
---
output:
pdf_document:
fig_caption: yes
fig_crop: no
---
```{r startup,echo=FALSE,results='hide',message=FALSE,tidy=FALSE,warning=FALSE,fig.keep='all',comment=NA}
require(knitr)
require(ggplot2)
opts_knit$set(progress = F, verbose = F)
opts_chunk$set(comment=NA,
tidy=FALSE,
warning=FALSE,
message=FALSE,
echo=FALSE,
dpi=600,
fig.width=6.75, fig.height=4, # Default figure widths
dev=c("pdf",'tiff'),
dev.args=list(pdf=list(NULL),tiff=list(compression='lzw')),
error=FALSE)
```
```{r plotloop,results='asis'}
for(x in seq(1,20)){
x1<-data.frame(x=seq(1,10),y=seq(1,10))
plt<-ggplot(data=x1,aes(x,y))+geom_point()
figLabel=paste('Figure',x,sep='')
capt<-paste('Caption for fig.',x)
cat(knit(text=(paste("```{r ",figLabel,",fig.pos='h',fig.cap='",capt,"'}\nplt\n```",sep=''))))
cat('\\newpage')
plot.knit function in knitr plots, labels, and captions within one chunk can be modified to account for the syntax of markdown as opposed to latex. plot.knit.md becomes
plot.knit.md<-function(chunkLabel,#text for chunk label which is also used for figure file name
capt,#text for caption
plt,
...)
{
cat(knit(text=knit_expand(text="```{r, {{chunkLabel}},eval=TRUE,fig.cap='{{capt}}',echo=FALSE}\nplt\n```"),
quiet=TRUE))
}
This works in the following markdown doc.
---
title: "plot.knit.md demo"
author: "Joel Allen"
date: "04/23/2015"
output:
html_document: default
pdf_document:
fig_caption: yes
---
This is an R Markdown document to demonstrate the generation of self-contained code chunks in a markdown file. It is particularly useful for situations where multiple plots are generated in a single code chunk allowing for dynamic label and caption support.
This example draws on
http://stackoverflow.com/questions/21685885/knitr-plots-labels-and-captions-within-one-chunk
in response to
https://stackoverflow.com/questions/27443019/knitr-plots-labels-and-captions-within-one-chunk-rmd-files
Items to note:
#. output pdf_document fig_caption option must be set to yes
#. plot.knit has been modified to plot.knit.md to account for the different syntax needed.
```{r, echo=FALSE,results='asis'}
plot.knit.md<-function(chunkLabel,#text for chunk label which is also used for figure file name
capt,#text for caption
plt,
...)
{
cat(knit(text=knit_expand(text="```{r, {{chunkLabel}},eval=TRUE,fig.cap='{{capt}}',echo=FALSE}\nplt\n```"),
quiet=TRUE))
}
require(ggplot2)
cars.p<-ggplot(cars,aes(x=speed,y=dist))+
geom_point()
plot.knit.md(chunkLabel="carsPlot",capt="this is a caption for the cars plot",plt=cars.p)
```
One thing to figure out though is the attachment of labels...
Does anybody use gridSVG in Knitr? I found package "gridSVG" provide a device named "gridsvg" and I've written code as follows.
```{r message=FALSE, echo=FALSE, warning=FALSE, results='hide', dev='gridsvg', fig.ext='svg'}
analysis.runner.result.plot(result, score.table, info.table) # which produces a gpplot
```
When I click "Knitr HTML", I got:
pandoc.exe: Could not find data file
AnalysisReport_files/figure-html/unnamed-chunk-61.svg pandoc document conversion failed
It seems that the gridsvg didn't produce svg file. I've searched the internet but failed to find any example that uses gridSVG in knitr.
How should I modify the code? (P.S. due to the render quality under windows, I don't want to use the default 'svg' device)
Thanks!
Update: with knitr >= v1.40, you can ignore the answer below and simply use the chunk option dev = 'gridSVG'.
Because gridSVG::gridsvg() is not a standard R graphics device, you cannot use the dev chunk option in knitr. The only way at the moment is to manually save the plots, and use a chunk hook to write the plots to your output (see the knitr graphics manual). Here is an example:
---
title: Save plots using gridSVG and knitr
author: Yihui Xie
output:
html_document: default
---
Set up a chunk hook for manually saved plots.
```{r setup}
library(knitr)
knit_hooks$set(custom.plot = hook_plot_custom)
```
A single plot.
```{r test-a, fig.keep='none', fig.ext='svg', custom.plot=TRUE}
library(ggplot2)
qplot(speed, dist, data = cars)
gridSVG::grid.export(fig_path('.svg'))
```
Multiple plots.
```{r test-b, fig.keep='none', fig.ext='svg', custom.plot=TRUE, fig.num=2, message=FALSE}
library(ggplot2)
p = qplot(speed, dist, data = cars)
p + geom_smooth()
gridSVG::grid.export(fig_path('svg', number = 1))
p + geom_jitter()
gridSVG::grid.export(fig_path('svg', number = 2))
```
See the source document of this post at
http://stackoverflow.com/q/23852753/559676
See output at http://rpubs.com/yihui/knitr-gridsvg