Table of Contents

What's new in ggplot2 1.0

ggplot2 1.0 RCが公式アナウンスされました。 https://twitter.com/hadleywickham/status/459732274112520192

最近ggplot2の開発に関わる時間と気力がないので、せめてもの・・・、ということでggplot2 1.0の新機能です。

地図の高速描画

素早く地図を書くための座標系。 coord_map()はプロジェクションを考慮するけど、coord_quickmap()は近似でやる。 アスペクト比を上手く扱ってくれるので、狭い領域ならcoord_quickmap()で十分。

以下の例は?coord_quickmapより。

nz <- map_data("nz")
nzmap <- ggplot(nz, aes(x = long, y = lat, group = group)) +
  geom_polygon(fill = "white", colour = "black")

# デカルト座標系(アスペクト比を考慮しない)
nzmap

plot of chunk unnamed-chunk-2

# メルカトル図法によるプロジェクション
nzmap + coord_map()

plot of chunk unnamed-chunk-2

# アスペクト比の近似
nzmap + coord_quickmap()

plot of chunk unnamed-chunk-2

大きな領域だと歪む

ussr <- subset(map_data("world"), region=="USSR" & long > 0)
ussrmap <- ggplot(ussr , aes(x = long, y = lat, group = group)) +
  geom_polygon(fill = "white", colour = "black")
# メルカトル図法によるプロジェクション
ussrmap + coord_map()

plot of chunk unnamed-chunk-3

# アスペクト比の近似
ussrmap + coord_quickmap()

plot of chunk unnamed-chunk-3

箱ひげ図の幅によるサンプルサイズの表現

varwidth=TRUEにすると箱ひげ図の幅がサンプルサイズの平方根に比例するようになる。

library(plyr)
set.seed(42)
d <- ldply(c(10, 100, 1000), function(x) data.frame(N=factor(x), V=rnorm(x)))
p <- ggplot(d, aes(N, V))
# 既定の動作
p + geom_boxplot()

plot of chunk unnamed-chunk-4

# 幅による可視化
p + geom_boxplot(varwidth=TRUE)
## Warning: position_dodge requires constant width: output may be incorrect

plot of chunk unnamed-chunk-4

jitterとdodgeの組み合わせによる位置指定

解説不要。

d2 <- mutate(d, G = factor(rbinom(nrow(d), 1, 0.5), labels=letters[1:2]))
p <- ggplot(d2, aes(N, V, colour = G, fill = G))
# jitterもdodgeもなし
p + geom_point()

plot of chunk unnamed-chunk-5

# jitter
p + geom_point(position = position_jitter(width = 0.2))

plot of chunk unnamed-chunk-5

# dodge
p + geom_point(position = position_dodge(width = 0.5))
## ymax not defined: adjusting position using y instead

plot of chunk unnamed-chunk-5

# jitter & dodge
p + geom_point(position = position_jitterdodge(jitter.width = 0.2, dodge.width = 0.5))

plot of chunk unnamed-chunk-5

xlimとylimで上限か下限のどっちかだけ範囲指定

昔から要望が多かった機能。 なお、xlimylimはスケーリングでの段階での範囲指定なので、範囲外のデータは可視化だけではなく統計計算からも除外されます。

x <- rnorm(10000)
# 範囲指定なし
qplot(x, geom="histogram")
## stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.

plot of chunk unnamed-chunk-6

# 両側範囲指定
qplot(x, geom="histogram") + xlim(-1, 1)
## stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.

plot of chunk unnamed-chunk-6

# 片側範囲指定
qplot(x, geom="histogram") + xlim(-1, NA)
## stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.

plot of chunk unnamed-chunk-6

brewerで連続値の色指定

color brewerのパレットを連続値の色で使えるようになった。

以下は?scale_fill_distillerの例を改変。

volcano3d <- reshape2::melt(volcano)
names(volcano3d) <- c("x", "y", "z")
v <- ggplot() + geom_tile(aes(x = x, y = y, fill = z), data = volcano3d) + coord_equal()

# デフォルト
v

plot of chunk unnamed-chunk-7

# scale_fill_distillerのデフォルト
v + scale_fill_distiller(guide = "colorbar")

plot of chunk unnamed-chunk-7

# パレット(黄色オレンジ赤の3色グラデーション)
v + scale_fill_distiller(palette = "YlOrRd", guide = "colorbar")

plot of chunk unnamed-chunk-7

散布図に楕円形の信頼区間領域を追加

見たまんま。計算方法等の詳細は?stat_ellipseで。

p <- ggplot(iris, aes(Sepal.Length, Petal.Length, colour = Species)) + geom_point()
# 既定の動作(多変量t分布)
p + stat_ellipse()

plot of chunk unnamed-chunk-8

# 多変量正規分布
p + stat_ellipse(type = "norm")

plot of chunk unnamed-chunk-8

# 中心からのユークリッド距離
p + lapply(1:4/4, function(x) stat_ellipse(type = "euclid", level = x)) + coord_equal()

plot of chunk unnamed-chunk-8

新しい白黒テーマとか

私は論文ではtheme_bwしてますが、theme_linedrawの方がいいですね。 サンプルは?ggthemeより。

p <- ggplot(mtcars) + geom_point(aes(x = wt, y = mpg,
     colour=factor(gear))) + facet_wrap(~am)
# theme_bw
p + theme_bw()

plot of chunk unnamed-chunk-9

# theme_linedraw
p + theme_linedraw()

plot of chunk unnamed-chunk-9

# theme_light
p + theme_light()

plot of chunk unnamed-chunk-9

ファセット用の新しいテーマパラメータ

個人的には、見た目にはあんまりこだわらないほうがいいと思います。時間の無駄です。

library(grid)
p + theme(panel.margin.x = unit(2, "char"))

plot of chunk unnamed-chunk-10

p + theme(panel.margin.x = unit(0, "null"))

plot of chunk unnamed-chunk-10

回転したテキストの縦方向の位置合わせ

マニアックですが、これ実装すると相当面倒なんです。 詳細はここで。

ファセットラベル用の関数

ファセットの行・列のタイトルのラベルを指定するための関数です。動作はややこしい。 引数で、ファセット用の変数名=ラベル用の関数、みたいに指定します。 ラベル用の関数が1引数なら、ファセットの値を引数にしてその関数が呼び出されます。 ラベル用の関数が2引数なら、ファセットの変数名と値を引数にしてその関数が呼び出されます。 ラベル用の関数ではなく、ファセットの値に対応した名前付きベクトルにしてもOKで、この場合はその水準に対応する値になります(意味分かんないですね。例を見て下さい)。

quartzFonts(mei = quartzFont(rep("Meiryo", 4)))

p1 <- ggplot(subset(mpg, cyl %in% c(4, 6)), aes(cty, hwy)) + geom_point() + theme_grey(base_family="mei")
# デフォルト
p1 + facet_grid(cyl ~ class)

plot of chunk unnamed-chunk-11

# cylに対してlabel_both(変数名:値)とする
p1 + facet_grid(cyl ~ class, labeller=labeller(cyl=label_both))

plot of chunk unnamed-chunk-11

# cylに対して1引数の関数
f <- function(x) paste0(x, " 気筒")
p1 + facet_grid(cyl ~ class, labeller=labeller(cyl=f))

plot of chunk unnamed-chunk-11

# 名前付きベクトルで指定
lbl <- c(`4` = "あいうえ", `6` = "おかき")
p1 + facet_grid(cyl ~ class, labeller=labeller(cyl=lbl))

plot of chunk unnamed-chunk-11

あと、長い説明を入れたときに自動改行する補助関数もできてますね。 ただし日本語だと空白入れないと改行されないのであんまり意味無いですね。

quartzFonts(mei = quartzFont(rep("Meiryo", 4)))
d <- mutate(subset(mpg, cyl %in% c(4, 6)), 
            cyl2 = factor(cyl, levels = c(4, 6), labels = c("この道をいけば どうなるものか", "迷わず行けよ 行けばわかるさ")))
p1 <- ggplot(d, aes(cty, hwy)) + geom_point() + theme_grey(base_family="mei")
p1 + facet_grid(class~cyl2, labeller=labeller(cyl2 = label_wrap_gen(6)))

plot of chunk unnamed-chunk-12

インストール

ggplot2 1.0 RCのインストールは

install.packages("devtools")
devtools::install_github("hadley/ggplot2@ggplot2-1.0.0-rc")

動作させた環境

sessionInfo()
## R version 3.0.2 (2013-09-25)
## Platform: x86_64-apple-darwin10.8.0 (64-bit)
## 
## locale:
## [1] ja_JP.UTF-8/ja_JP.UTF-8/ja_JP.UTF-8/C/ja_JP.UTF-8/ja_JP.UTF-8
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] plyr_1.8       pings_1.0      pingr_0.1      mapproj_1.2-2 
## [5] maps_2.3-6     dplyr_0.1.1    devtools_1.4.1 ggplot2_1.0.0 
## [9] knitr_1.5.22  
## 
## loaded via a namespace (and not attached):
##  [1] assertthat_0.1     audio_0.1-5        codetools_0.2-8   
##  [4] colorspace_1.2-4   dichromat_2.0-0    digest_0.6.4      
##  [7] evaluate_0.5.1     formatR_0.10       grid_3.0.2        
## [10] gtable_0.1.2       httr_0.2           labeling_0.2      
## [13] MASS_7.3-29        memoise_0.1        munsell_0.4.2     
## [16] parallel_3.0.2     proto_0.3-10       RColorBrewer_1.0-5
## [19] Rcpp_0.11.0        RCurl_1.95-4.1     reshape2_1.2.2    
## [22] scales_0.2.3       stringr_0.6.2      tools_3.0.2       
## [25] whisker_0.3-2