読者です 読者をやめる 読者になる 読者になる

ggplot2 の geom_text() 関数で fontfamily をいじってみよう

ggplot2-0.9.x では修正済です

require(ggplot2)
t <- c("a", "b", "c")
x <- c(1, 2, 3)
y <- c(2, 2, 2)
d <- data.frame(x, y, t)
windowsFonts(serif = "Times New Roman")
p <- ggplot(data = d, aes(x = x, y = y, label = t)) +
  geom_text(size = 16 * 0.282, family = "serif") +
  theme_bw(base_size = 16, base_family = "serif")
print(p)

ただし、文字サイズを theme_xxbase_size 指定した大きさと同じにするためには、0.282 をかけなくてはいけない。

古い情報

ggplot2 は grid 系グラフィックスなので、grid.gedit() を使うと fontfamily を変更できるらしい。
参考 Using CJK Fonts in R and ggplot2 (Hi!!: Kohske Takahashi)

require(ggplot2)
t <- c("a", "b", "c")
x <- c(1, 2, 3)
y <- c(2, 2, 2)
d <- data.frame(x,y,t)

mytheme_gray <- function (base_size = 12, family = "") {
  structure(list(
    axis.line = theme_blank(),
    axis.text.x = theme_text(family = family, size = base_size * 0.8,
      lineheight = 0.9, colour = "grey50", vjust = 1), 
    axis.text.y = theme_text(family = family, size = base_size * 0.8,
      lineheight = 0.9, colour = "grey50", hjust = 1),
    axis.ticks = theme_segment(colour = "grey50"), 
    axis.title.x = theme_text(family = family, size = base_size, vjust = -0.5), 
    axis.title.y = theme_text(family = family, size = base_size, angle = 90, 
      vjust = 0.5),
    axis.ticks.length = unit(0.15, "cm"), 
    axis.ticks.margin = unit(0.2, "cm"),
    legend.background = theme_rect(colour = "white"), 
    legend.key = theme_rect(fill = "grey95", colour = "white"), 
    legend.key.size = unit(1.2, "lines"),
    legend.text = theme_text(family = family, size = base_size * 0.8),
    legend.title = theme_text(family = family, size = base_size * 0.8,
      face = "bold", hjust = 0),
    legend.position = "right",
    panel.background = theme_rect(fill = "grey90", colour = NA), 
    panel.border = theme_blank(),
    panel.grid.major = theme_line(colour = "white"), 
    panel.grid.minor = theme_line(colour = "grey95", size = 0.25), 
    panel.margin = unit(0.25, "lines"),
    strip.background = theme_rect(fill = "grey80", colour = NA),
    strip.text.x = theme_text(family = family, size = base_size * 0.8),
    strip.text.y = theme_text(family = family, size = base_size * 0.8,
      angle = -90),
    plot.background = theme_rect(colour = NA, fill = "white"),
    plot.title = theme_text(family = family, size = base_size * 1.2),
    plot.margin = unit(c(1, 1, 1, 0.5), "lines")), class = "options")
}

windowsFonts(serif="Times New Roman")
p <- ggplot(data=d, aes(x=x, y=y, label=t)) + geom_text() +
  mytheme_gray(base_size=26, family="serif")
png("001.png", width = 7, height = 7, units ="in", res=300)
p
grid.gedit("text", gp=gpar(fontfamily="serif"))
dev.off()

png("002.png", width = 7, height = 7, units ="in", res=300)
p
dev.off()


ということで昔言及した geom_text() の font が変わらない病 はこうすると良いようです。