ggplot2 bar_plot with label

エクセル脳の皆さん、こんにちは。
ggplot2で棒グラフを描いた時にラベルが欲しくなること、あると思います。

library(ggplot2)
library(plyr)
iris.mod <- ddply(iris, .(Species), summarise, mean.S.L = mean(Sepal.Length))
ggplot(iris.mod, aes(x = Species, y = mean.S.L)) + geom_bar()

plot of chunk unnamed-chunk-1

そんな時はgeom_textでラベルを付けます。

ggplot(iris.mod, aes(x = Species, y = mean.S.L, label = mean.S.L)) + 
    geom_bar() + geom_text(aes(y = mean.S.L))

plot of chunk unnamed-chunk-2

そのまま指定すると、ラベルが棒にかかってしまうので微調整します。

ggplot(iris.mod, aes(x = Species, y = mean.S.L, label = mean.S.L)) + 
    geom_bar() + geom_text(aes(y = mean.S.L + 0.2))

plot of chunk unnamed-chunk-3

一つだけラベルをつけたい時はannotateが便利です。

ggplot(iris.mod, aes(x = Species, y = mean.S.L)) + geom_bar() + annotate(x = "virginica", 
    y = iris.mod[iris.mod$Species == "virginica", ]$mean.S.L + 0.2, geom = "text", 
    label = iris.mod[iris.mod$Species == "virginica", ]$mean.S.L)

plot of chunk unnamed-chunk-4

これでまた一歩Rもエクセルに一歩近づきましたね。enjoy!