3 min read

knitr figure

knitr + Rmarkdown + pandocメモ

YAML

---
title: "MyYAML"
author: "Keach Murakami"
date: "2018-05-05 16:58:16"
bibliography: ~/GitHub/BeeLabR/BibTex/Full.bib
header-includes:
  - \setmainfont{Helvetica Neue} 
  - \usepackage{zxjatype} # 日本語を使うためのパッケージ
  - \setjamainfont{Hiragino Kaku Gothic Pro} # 日本語フォントの指定
  - \usepackage{lscape} # 図を回転するためのパッケージ
  - \newcommand{\blandscape}{\begin{landscape}} # 図回転用のbegin command
  - \newcommand{\elandscape}{\end{landscape}} # 図回転用のend command
  - \usepackage{setspace} # 行間の調節ためのパッケージ
  - \newcommand{\bdoublespace}{\begin{spacing}{1.5}} # 行間を広げるbegin command
  - \newcommand{\edoublespace}{\end{spacing}{}} # 行間を広げるbegin command
  - \usepackage{lineno} # 行番号を追加するためのパッケージ
  - \linenumbers # 行番号を追加する

output:
  pdf_document:
    latex_engine: xelatex
    toc: TRUE
    toc_depth: 3
    fig_caption: TRUE
  html_document:
    theme: sandstone
    self_contained: TRUE
    fig_caption: TRUE
---

行番号をつける・ダブルスペースにする

Set double spacing and line numbers when converting from Markdown to PDF with pandoc

Setup chunk

# knitrごとに読み込まれているオブジェクトを全消去
rm(list = ls())

# ggplotの作図用。デフォルトの大きさを指定
base_size_default <- 12 

# 数式・図・表にオートで番号付け
devtools::source_url("https://raw.githubusercontent.com/KeachMurakami/Sources/master/TeX_accessory.R")
EqnHead <- "4-"
FigHead <- "Fig. 4-"
TableHead <- "Table 4-"

knitr::opts_chunk$set(echo = FALSE, fig.width = 5, fig.height = 5,
                      out.width = '500pixel', out.height = '500pixel', dpi = 100,
                      message = FALSE, warning = FALSE, cache = F, eval = T)

knitr + rmarkdownで図の大きさ調節

  • fig.width/height
    • 図のプロットのサイズ
    • インチ単位
  • out.width/height
    • 図を出力した際のサイズ
    • 拡大/縮小コピー的な
      • LaTeX: .8\linewidth, 3in, 8cm, 40% (= 0.4)…
      • HTML: 300px, 5cm, 3in, 40%…
  • out.extra
    • out.extra=’angle=90’など
    • 任意文字を引数として受け取るので、自由に編集できるらしい
    • html images にも使える (extra options will be written into the tag, e.g. out.extra=‘style=“display:block;”’)
# {r, fig.width = 5, fig.height = 5, out.width = '50%'}
plot(sin(1:100), type = "l")

# {r, fig.width = 2, fig.height = 2, out.width = '50%'}
# 小さく書いたのを拡大するイメージ
plot(sin(1:100), type = "l")

# {r, fig.width = 7, fig.height = 7, out.width = '50%'}
# 大きく書いたのを縮小するイメージ
plot(sin(1:100), type = "l")

図のキャプションにhtmlタグを直打ちする

図のキャプションに特殊文字、上付き文字、斜体を使う場合など
chunk optionにそのままhtmlタグ入りの文字列を入れると、fig.cap以下の引数が無視される

caption_html <- 
  "with html tag <i>test</i><sup>test</sup>."
caption_plain <- 
  "without html tag testtest."

knitr::opts_chunk$set(fig.width = 5)

htmlタグなしの場合のhtmlのソース
{r, fig.cap = caption_plain}

<img src="略=" alt="without html tag testtest." width="480">
<p class="caption">
without html tag testtest.
</p>

htmlタグありの場合のhtmlのソース
{r, fig.cap = caption_html}
.&quot;のあたりでタグがコンタミしているため、fig.widthに引数が届いていない

<img src="略=" alt="with html tag &lt;i&gt;test&lt;/i&gt;&lt;sup&gt;test&lt;/sup&gt;.&quot; width=“480” /&gt;
&lt;p class=" caption">
with html tag <i>test</i><sup>test</sup>.
</p>

こういうときのためにknit_hooksがある
chunkの表示だったり実行だったりを自分好みにする
setup chunkで読み込むのがよい

knitr::knit_hooks$set(html.cap = function(before, options, envir) {
  if(!before) {
    paste0('<p class="caption">', options$html.cap, "</p>")
  }
})

hookしたタグありの場合のhtmlのソース
{r, html.cap = caption_html}

<img src="略=" width="480" />
<p class="caption">
with html tag <i>test</i><sup>test</sup>.
</p>

ローカルの画像を直接貼り付ける

Drawソフトで書いた画像、あるいは写真を貼付ける、といった場合、2つの方法がある

  1. html部にmarkdown記法 (直書き)
    html部に![図のキャプション](/path/to/image)と直書きする 図のキャプションをhtml書きしないといけなかったり、変数として扱えなかったり、と面倒が多い

  2. chunk内にknitr::include_graphics

knitr::include_graphics(path = "path/to/image")

参考ページ

R markdown(knitr)パッケージのchunk optionまとめ
Chunk options and package options
caption in the html output of knitr
How to set size for local image using knitr for markdown?

devtools::session_info()
## Session info -------------------------------------------------------------
##  setting  value                       
##  version  R version 3.5.0 (2018-04-23)
##  system   x86_64, darwin15.6.0        
##  ui       X11                         
##  language (EN)                        
##  collate  en_US.UTF-8                 
##  tz       Asia/Tokyo                  
##  date     2018-05-05
## Packages -----------------------------------------------------------------
##  package   * version date       source        
##  backports   1.1.2   2017-12-13 CRAN (R 3.5.0)
##  base      * 3.5.0   2018-04-24 local         
##  blogdown    0.6     2018-04-18 CRAN (R 3.5.0)
##  bookdown    0.7     2018-02-18 CRAN (R 3.5.0)
##  compiler    3.5.0   2018-04-24 local         
##  datasets  * 3.5.0   2018-04-24 local         
##  devtools    1.13.5  2018-02-18 CRAN (R 3.5.0)
##  digest      0.6.15  2018-01-28 CRAN (R 3.5.0)
##  evaluate    0.10.1  2017-06-24 CRAN (R 3.5.0)
##  graphics  * 3.5.0   2018-04-24 local         
##  grDevices * 3.5.0   2018-04-24 local         
##  htmltools   0.3.6   2017-04-28 CRAN (R 3.5.0)
##  knitr       1.20    2018-02-20 CRAN (R 3.5.0)
##  magrittr    1.5     2014-11-22 CRAN (R 3.5.0)
##  memoise     1.1.0   2017-04-21 CRAN (R 3.5.0)
##  methods   * 3.5.0   2018-04-24 local         
##  Rcpp        0.12.16 2018-03-13 CRAN (R 3.5.0)
##  rmarkdown   1.9     2018-03-01 CRAN (R 3.5.0)
##  rprojroot   1.3-2   2018-01-03 CRAN (R 3.5.0)
##  stats     * 3.5.0   2018-04-24 local         
##  stringi     1.1.7   2018-03-12 CRAN (R 3.5.0)
##  stringr     1.3.0   2018-02-19 CRAN (R 3.5.0)
##  tools       3.5.0   2018-04-24 local         
##  utils     * 3.5.0   2018-04-24 local         
##  withr       2.1.2   2018-03-15 CRAN (R 3.5.0)
##  xfun        0.1     2018-01-22 CRAN (R 3.5.0)
##  yaml        2.1.18  2018-03-08 CRAN (R 3.5.0)