LoginSignup
3
3

More than 5 years have passed since last update.

Knitrの出力部分で日本語固定幅フォントを使う

Last updated at Posted at 2015-10-13

KnitrでCustom CSSを使う

R Markdown Document

適用前
default_style.png

適用後
monospaced_font.png

設定方法

cssファイルを作る

font-familyの先頭に'MS Gothic'を指定
(それ以外は英数字のみの場合に推奨されていると思われるものを流用した)

styles.css
tt, code, pre {
   font-family: 'MS Gothic', 'DejaVu Sans Mono', 'Droid Sans Mono', 'Lucida Console', Consolas, Monaco, monospace;
}

今回は実行するRMarkdownファイルと同じフォルダ内にファイルを作成

R Markdownでcssを読み込む設定を追加する

---
title: "Hoge"
output:
  html_document:
    css: styles.css
---

気付いた点

  • RStudio組み込みのビューアーでは固定幅にならなかった。ChromeでOKだった
    • 'MS Gothic'が読み込めてない可能性
    • MS Officeがインストールされているかで結果が違う可能性
  • 日本語を含まなければ、'MS Gothic'以外の指定で十分かもしれない
  • font-family'MS ゴシック'を指定したらうまくいかなかった
    • ソースなどで見るとcssのコードの部分が文字化けしていた
    • 指定箇所は<link href="data:text/css, ...のようになっている
    • self_contained: falsehtml_documentの子として指定すると、js,cssファイルが外部ファイルのまま参照される
  • MacではOsaka-Monoも追加しておいて良いかもしれない

試した環境はMac, RStudio

その他

結果出力部分を画面いっぱいに使うスタイルも試した

styles.css
.main-container {
    max-width: none !important;
}

RMarkdownのオプション

\```{r set-options, echo=FALSE, cache=FALSE}
options(width = 130)
\```

DT

データの量次第ではDTを使えばそれで良い場合もある

テストコード

データ表示部分
日本語のデータの列を追加(一番左の列)

iris
orig_names <- names(iris)

iris$ <- NA
iris[iris$Species=='setosa',]$ <- 'セトサ'
iris[iris$Species=='versicolor',]$ <- 'ヴァージカラー'
iris[iris$Species=='virginica',]$ <- 'ヴァージニカ'

iris <- iris[,c('種', orig_names)]

# 適当に並べ替え
iris[order(iris$Sepal.Width, iris$Petal.Length),]
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3