rr-markdowncairobookdown

Cairo pdf doesn't work properly due to "out of memory" in R


I'm trying to produce a pdf document with a graphic created with some R functions, like plot() or ggplot(). Since I use a Windows machine, I need to call cairo_pdf to change the font-family of the plot and to embed another fonts I specify.

I have successfully knit the pdf document with plots created with cairo on my Windows 10. However, when I try to knit the document on my Windows 8.1, I always receive the following error message:

Quitting from lines 22-23 (test.Rmd) 
Error in (function (filename = if (onefile) "Rplots.pdf" else "Rplot%03d.pdf",  : 
  unable to start device 'cairo_pdf'
Calls: <Anonymous> ... block_exec -> chunk_device -> dev_new -> do.call -> <Anonymous>
In addition: Warning messages:
1: In strsplit(info, "\n") : input string 3 is invalid in this locale
2: In strsplit(info, "\n") : input string 3 is invalid in this locale
3: In (function (filename = if (onefile) "Rplots.pdf" else "Rplot%03d.pdf",  :
  cairo error 'out of memory'
Execution halted

I'm wondering why cairo_pdf causes out-of-memory problem, even though RStudio R Session doesn't consume much memory when I knit the document (I checked the memory RStudio R Session occupied is stable in my system by Task Manager). Also, I'm totally not sure why R looks for Rplots.pdf or Rplot%03d.pdf, though both of them do not exist in my current directory nor in my system... Is this OS-specific problem? Or do I fail to set a path of cairo_pdf?

MWE

---
output:
  bookdown::pdf_book:
    base_format: "function(..., number_sections)         
rmarkdown::beamer_presentation(...)"
    number_sections: false
    keep_tex: yes
    latex_engine: lualatex
    theme: "AnnArbor"
    colortheme: "dolphin"
    fonttheme: "structurebold"
    slide_level: 1
    toc: false
    fig_caption: TRUE
    dev: cairo_pdf
    citation_package: natbib
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## 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, dev.args = list(family = "Garamond")}
plot(pressure, main = "A plot whose characters are Garamond")
```

Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.

Session Information

> sessionInfo()
R version 3.5.2 (2018-12-20)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 8.1 x64 (build 9600)

Matrix products: default

locale:
[1] LC_COLLATE=Japanese_Japan.932  LC_CTYPE=Japanese_Japan.932    LC_MONETARY=Japanese_Japan.932
[4] LC_NUMERIC=C                   LC_TIME=Japanese_Japan.932    

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] jpndistrict_0.3.2   numDeriv_2016.8-1   optimx_2018-7.10    lemon_0.4.3        
 [5] DiagrammeR_1.0.0    ggsci_2.9           kableExtra_1.0.1    pbkrtest_0.4-7     
 [9] effects_4.1-0       car_3.0-2           carData_3.0-2       languageR_1.5.0    
[13] coefplot_1.2.6      ggrepel_0.8.0       lmerTest_3.1-0      lme4_1.1-20        
[17] Matrix_1.2-15       data.table_1.12.0   reshape_0.8.8       formattable_0.2.0.1
[21] knitr_1.21          forcats_0.4.0       stringr_1.4.0       dplyr_0.8.0.1      
[25] readr_1.3.1         tidyr_0.8.2         tibble_2.0.1        tidyverse_1.2.1    
[29] ggspatial_1.0.3     purrr_0.3.0         sf_0.7-2            xtable_1.8-3       
[33] jpmesh_1.1.1        gdata_2.18.0        ggjoy_0.4.1         ggridges_0.5.1     
[37] gridExtra_2.3       ggplot2_3.1.0       magrittr_1.5        nnet_7.3-12        
[41] MASS_7.3-51.1       lattice_0.20-38     needs_0.0.3        

loaded via a namespace (and not attached):
 [1] useful_1.2.6       minqa_1.2.4        colorspace_1.4-0   class_7.3-14      
 [5] rio_0.5.16         leaflet_2.0.2      rstudioapi_0.9.0   lubridate_1.7.4   
 [9] xml2_1.2.0         splines_3.5.2      jsonlite_1.6       nloptr_1.2.1      
[13] broom_0.5.1        shiny_1.2.0        compiler_3.5.2     httr_1.4.0        
[17] backports_1.1.3    assertthat_0.2.0   lazyeval_0.2.1     survey_3.35-1     
[21] cli_1.0.1          later_0.8.0        visNetwork_2.0.5   htmltools_0.3.6   
[25] tools_3.5.2        igraph_1.2.4       gtable_0.2.0       glue_1.3.0        
[29] reshape2_1.4.3     Rcpp_1.0.0         rgexf_0.15.3       cellranger_1.1.0  
[33] nlme_3.1-137       crosstalk_1.0.0    xfun_0.5           openxlsx_4.1.0    
[37] rvest_0.3.2        mime_0.6           miniUI_0.1.1.1     gtools_3.8.1      
[41] XML_3.98-1.17      scales_1.0.0       hms_0.4.2          promises_1.0.1    
[45] parallel_3.5.2     RColorBrewer_1.1-2 yaml_2.2.0         curl_3.3          
[49] downloader_0.4     stringi_1.3.1      Rook_1.1-1         e1071_1.7-0.1     
[53] zip_1.0.0          rlang_0.3.1        pkgconfig_2.0.2    evaluate_0.13     
[57] htmlwidgets_1.3    tidyselect_0.2.5   plyr_1.8.4         bookdown_0.9      
[61] R6_2.4.0           generics_0.0.2     DBI_1.0.0          pillar_1.3.1      
[65] haven_2.1.0        foreign_0.8-71     withr_2.1.2        units_0.6-2       
[69] survival_2.43-3    abind_1.4-5        modelr_0.1.4       crayon_1.3.4      
[73] rmarkdown_1.11     viridis_0.5.1      readxl_1.3.0       influenceR_0.1.0  
[77] webshot_0.5.1      digest_0.6.18      classInt_0.3-1     httpuv_1.4.5.1    
[81] brew_1.0-6         munsell_0.5.0      viridisLite_0.3.0


>RStudio.Version()$version
[1] ‘1.2.1280’

Also I've installed Cairo and cairoDevice package.


Solution

  • I'm not sure, but somehow the problem was solved by installing the latest R (R 3.6.0 in my case) and by adding dev = "cairo_pdf" to knitr::opts_chunk$set()...

    ---
    title: "The definitive MWE"
    subtitle: "Oh, yeah"
    author: "CLR"
    institute: "CLR's office"
    abstract: "This should work!"
    output:
      bookdown::pdf_document2:
        number_sections: true
        latex_engine: xelatex
        keep_tex: true
        toc: false
        fig_caption: TRUE
    dev: cairo_pdf #Cairo_pdf <- cairoDevice, CairoPDF <- Cairo
    citation_package: natbib
    documentclass: bxjsarticle #Replace this with the document class you use
    classoption: pandoc,everyparhook=compat #These options are suitable for bxjsarticle
    indent: true
    fontsize: 10pt
    geometry: "left=2cm,right=2cm,top=2cm,bottom=3cm"
    always_allow_html: yes
    link-citations: yes
    ---
    
    ```{r}
    knitr::opts_chunk$set(fig.path = "somewhere/you/want/to/store/your/awesome/figs", 
                          fig.height=6, 
                          fig.width=8,
                          fig.align="center",
                          echo=FALSE,
                          message = FALSE,
                          warning = FALSE,
    
                          #Select the same device as the one you specified in YAML section
                          dev = "cairo_pdf", 
    
                          #Put the name of your favorite font into ""
                          dev.args = list(family = "Source Han Sans JP Normal")
                          ) 
    ```
    
    
    ```{r cars}
    library(ggplot2)
    a=ggplot(cars, aes(x=speed, y=dist))+
      geom_point()+
      xlab("速度")
    a
    ```