問題
以下のようにggplot2で作成した日本語入りグラフを,ggsaveを用いてPNGで保存していたが,PDFで保存したほうがよいのでファイル名の拡張子をPDFに変えたところ,保存できなくなった.
library(ggplot2) p1 <- ggplot(data, aes(x = hoge, y = fuga)) + geom_point() + labs(y = "yじくじく軸") ggsave(file = "plot.png", plot = p1, height = 4, width = 5)
↓
library(ggplot2) p1 <- ggplot(data, aes(x = hoge, y = fuga)) + geom_point() + labs(y = "yじくじく軸") ggsave(file = "plot.pdf", plot = p1, height = 4, width = 5)
エラーメッセージはこう.
Error in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, : invalid font type In addition: There were 50 or more warnings (use warnings() to see the first 50)
環境
- wsl2(Ubuntu 20.04)
- R version 4.2.1
- RStudio Server 2022.02.3+492 (Prairie Trillium) for Ubuntu Bionic
日本語フォントは導入済み.
解決
こちらのブログを見て解決した. what-alnk.hatenablog.com
ggsaveのdevice
パラメータを指定すればいいっぽい.
library(ggplot2) p1 <- ggplot(data, aes(x = hoge, y = fuga)) + geom_point() + labs(y = "yじくじく軸") ggsave(file = "plot.pdf", plot = p1, device=cairo_pdf, height = 4, width = 5)
同じような問題が紹介されているブログがあったがMacでの解決策(quartzを使用する)しか書かれてなかったのでメモ書き.