J

ggplot2 のテーマを作成

f:id:joker1110:20120217205728p:image:w360

2012-10-31追記—ggplot2 0.9.2 のテーマを作成 - joker8phoenixの日記
(以下の内容は0.9.1以前の古いバージョンに対応しています。)

ggplot2 ではデフォルトでも十分美しいグラフが描ける。しかし、灰色の背景や、フォント、軸線、などなどを変更したいかもしれない。ここでは、テーマを定義し利用する。このテーマを自分でカスタマイズすれば、ある程度思い通りのグラフが描けるだろう。ここで作成しているテーマは、mytheme()という関数名にしている。その内部に定義している変数(axis.text.xなど)はggplot2の凡例やタイトルの色や位置を変更 -- opts()でできること - joker8phoenix の日記を参照すると良い。

library(ggplot2)
library(ggExtra)
quartzFonts(HiraMaru=quartzFont(rep(c("HiraMaruProN-W3","HiraMaruProN-W6"), 2)))
quartzFonts(HiraKaku=quartzFont(rep(c("HiraKakuProN-W3","HiraKakuProN-W6"), 2)))

##############
### colour ###
##############
cCyan <- "#00a0e9"
cMagenta <- "#e4007f"
cGreen <- "#009944"
cOrange <- "#f39800"
cLightBlue <- "#0068b7"
qcolours <- c(cCyan,cMagenta,cGreen,cLightBlue,cOrange)
scolours = colorRampPalette(c(cCyan,"grey60",cOrange))

#############
### theme ###
#############
mytheme <- function (
  base_size=20,
  title="",
  margin.top=1,
  margin.side=1,
  base_family="HiraKaku",
  number_family="Helvetica"
  ) {
  structure(list(
    title=title,
    axis.text.x=theme_text(family=number_family, size=base_size*0.8, 
                           lineheight=0.9, colour="black", vjust=1),
    axis.text.y=theme_text(family=number_family, size=base_size*0.8, 
                           lineheight=0.9, colour="black", hjust=1),
    axis.title.x=theme_text(family=base_family, size=base_size, vjust=0.5,hjust=0.9), 
    axis.title.y=theme_text(family=base_family, size=base_size, vjust=0.5, hjust=0.9,angle=90),
    axis.line=theme_segment(colour="black"),
    axis.ticks=theme_segment(colour="grey50"), 
    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="white", colour="white"), 
    legend.key.size=unit(1.2, "lines"),
    legend.text=theme_text(family=base_family, size=base_size*0.8),
    legend.title=theme_text(family=base_family, size=base_size*0.8,
                            face="bold", hjust=0),
    legend.position="right",
    panel.background=theme_blank(),
    panel.border=theme_blank(),
    panel.margin=unit(0.25, "lines"),
    panel.grid.major=theme_line(colour="white"), 
    panel.grid.minor=theme_line(colour="white", size=0.25), 
    plot.background=theme_blank(),
    plot.title=theme_text(family=base_family, size=base_size*1.0,
                          face="bold", vjust=1),
    plot.margin=unit(c(margin.top, margin.side, margin.top, margin.side), "lines"),
    strip.background=theme_rect(fill="grey80",colour="black"),
    strip.text.x=theme_text(family=base_family,face="plain",colour="black",size=base_size*0.8,hjust=0.5,vjust=0.5,angle=0,lineheight=0),
    strip.text.y=theme_text(family=base_family,face="plain",colour="black",size=base_size*0.8,hjust=0.5,vjust=0.5,angle=-90,lineheight=0)
    ), class = "options")
}

このテーマをmyggplot2.Rとして保存して呼び出すには、冒頭に

source("~/[ファイルの場所]/myggplot2.R")

とすれば良い。