library(ggforma)
library(grid)
library(systemfonts)

options <- list(sans = c("Arial", "Liberation Sans", "DejaVu Sans"), zh = c("Microsoft YaHei", 
"Noto Sans CJK SC", "PingFang SC"), ja = c("Yu Gothic", "Noto Sans CJK JP", 
"Hiragino Sans"), ko = c("Malgun Gothic", "Noto Sans CJK KR", 
"Apple SD Gothic Neo"))
installed <- system_fonts()$family
fonts <- vapply(options, function(x) {
  found <- intersect(x, installed)
  if (!length(found)) stop('Choose a suitable installed local font for ', paste(x, collapse = ', '))
  found[1L]
}, character(1))

sheet <- function(title, subtitle) {
  grid.newpage()
  grid.draw(markup_grob(title, format = "plain", x = .055, y = .925, hjust = 0,
                        size = 22, family = fonts["sans"], face = "bold", colour = "#172C3C"))
  grid.draw(markup_grob(subtitle, format = "plain", x = .055, y = .810, hjust = 0,
                        size = 10, family = fonts["sans"], colour = "#465865"))
  grid.lines(x = c(.055, .945), y = c(.745, .745), gp = gpar(col = "#CED7DA", lwd = .8))
}

note <- function(text, x, y, size = 17, family = fonts["sans"], ...) {
  grid.draw(markup_grob(text, x = x, y = y, size = size, family = family,
                        colour = "#172C3C", hjust = 0, ...))
}

key <- function(text, x, y) note(text, x, y, size = 9, face = "bold", format = "plain")

cjk <- function() {
  sheet("Three languages in one figure", "Local typefaces set a label for monthly library use in Chinese, Japanese and Korean.")
  samples <- c(zh = "图书馆月度访问量", ja = "図書館の月別利用者数", ko = "도서관 월별 방문 횟수")
  for (i in seq_along(samples)) {
    lang <- names(samples)[i]
    y <- c(.615, .425, .235)[i]
    key(c("CHINESE", "JAPANESE", "KOREAN")[i], .067, y)
    note(samples[i], .32, y, family = fonts[lang], lang = lang, size = 20)
  }
}

cjk()
