3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Google Colab の Rノートブックでggplot2グラフに日本語を表示

Last updated at Posted at 2020-12-14

Google Colab でRを動かすと、はじめは ggplotのグラフで日本語が文字化けしてしまいます。

library(ggplot2)

qplot(1:5, 1:5) +
  xlab("エックス軸") + ylab("ワイ軸") + ggtitle("タイトル")

これは、日本語フォントがインストールされていないためです。ColabはUbuntu上で動いているので、apt-get コマンドを使ってフォントを追加することが可能です。Rノートブックではシェルマジックが使えないので、system 関数を用います。

system("apt-get install -y fonts-noto-cjk")

フォントの一覧を表示。

systemfonts::system_fonts()

実際にはまだまだありますが省略。基本的に "CJK" が付いているフォントは日本語に対応しています(Chinese Japanese Korean の略なので)。

例えば、"Noto Sans CJK JP" をフォントに指定すると、ちゃんと日本語が表示されます。

qplot(1:5, 1:5) +
  xlab("エックス軸") + ylab("ワイ軸") + ggtitle("タイトル") +
  theme(text=element_text(family="Noto Sans CJK JP"))

"Serif" フォントを選ぶと明朝っぽくなります。

qplot(1:5, 1:5) +
  xlab("エックス軸") + ylab("ワイ軸") + ggtitle("タイトル") +
  theme(text=element_text(family="Noto Serif CJK JP"))

theme_update を使って、指定のフォントをデフォルトに設定することも可能です。

theme_update(text=element_text(family="Noto Sans CJK JP"))
qplot(1:5, 1:5) +
  xlab("エックス軸") + ylab("ワイ軸") + ggtitle("タイトル")
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?