Rで、directlabelsライブラリを使うと、折れ線や散布図、等高線などのプロットに対して、簡単に、かつ、もろもろ取りまとめて良い感じに?ラベルを出力することができる。
# install.packages("directlabels")
library(directlabels)
プロットオブジェクトを作成したら、それをdirectlabelsの関数へ渡すだけでラベル付けしてくれる。
なお、ラベル化される変数は、fillやcolourに指定したもの。
引数のpositioning methodsに、「ラベル位置の決め方」を指定することで、良きにレイアウトしてくれる。
p <- ggplot(…, aex(colour = [label's value])
direct.label(p, [positioning methods])
下記では、プロット種別ごとにpositioning methods(ラベル位置)をいくつかピックアップした。
散布図
ラベル位置に"smart.grid"を指定することで、グループの中心に(探索して)ラベルを出力する。
p <- ggplot(iris,aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
geom_point()
direct.label(p, "smart.grid")
ラベル位置に"extreme.grid"を指定することで、グループの端(四隅のどこか?)にラベルを出力する。
direct.label(p, "extreme.grid")
数値をラベルに指定した場合も、問題なく動作する。
ポイント描画のじゃまにならない程度にラベルを配置してくれるイメージ。
(ただ、処理時間は比較的長い)
p <- ggplot(iris,aes(x=Sepal.Length, y=Sepal.Width, color=Sepal.Width)) +
geom_point()
direct.label(p, "smart.grid")
折れ線グラフ
# 描画用データ準備
df <- data.frame(WorldPhones) %>%
tibble::rownames_to_column("Year") %>%
gather(key="Country", value="Users", -Year) %>%
mutate(Year=as.integer(Year))
# (下のような形式であればデータは何でもよい)
> head(df)
Year Country Users
1 1951 N.Amer 45939
2 1956 N.Amer 60423
3 1957 N.Amer 64721
4 1958 N.Amer 68484
5 1959 N.Amer 71799
6 1960 N.Amer 76036
ラベル位置に"first.qp"を指定することで、折れ線の先頭にラベルを出力する。
p <- ggplot(df, aes(x=Year, y=Users, colour=Country)) +
geom_line()
directlabels::direct.label(p, method="first.qp")
ラベル位置に"last.qp"を指定することで、折れ線の末尾にラベルを出力する。
directlabels::direct.label(p, method="last.qp")
ラベル位置に"angled.boxes"を指定することで、折れ線の適当な位置に矩形のラベルを出力する。
directlabels::direct.label(p, method="angled.boxes")
等高線図
ラベル位置に"top.pieces"を指定することで、各レベルの等高線の上側にラベルを出力する。
p <- ggplot(faithfuld, aes(waiting, eruptions, z = density)) +
geom_contour(aes(colour=..level..))
direct.label(p, "top.pieces")
ラベル位置に"top.pieces"を指定することで、各レベルの等高線の下側にラベルを出力する。
direct.label(p, "bottom.pieces")







