1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ggplotでプロット内へのラベル出力を効率的に(directlabels)

1
Posted at

Rで、directlabelsライブラリを使うと、折れ線や散布図、等高線などのプロットに対して、簡単に、かつ、もろもろ取りまとめて良い感じに?ラベルを出力することができる。

R
# install.packages("directlabels")
library(directlabels)

プロットオブジェクトを作成したら、それをdirectlabelsの関数へ渡すだけでラベル付けしてくれる。
なお、ラベル化される変数は、fillやcolourに指定したもの。
引数のpositioning methodsに、「ラベル位置の決め方」を指定することで、良きにレイアウトしてくれる。

R
p <- ggplot(, aex(colour = [label's value])
direct.label(p, [positioning methods])

下記では、プロット種別ごとにpositioning methods(ラベル位置)をいくつかピックアップした。

散布図

ラベル位置に"smart.grid"を指定することで、グループの中心に(探索して)ラベルを出力する。

R
p <- ggplot(iris,aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
  geom_point()
direct.label(p, "smart.grid")

image.png

ラベル位置に"extreme.grid"を指定することで、グループの端(四隅のどこか?)にラベルを出力する。

R
direct.label(p, "extreme.grid")

image.png

数値をラベルに指定した場合も、問題なく動作する。
ポイント描画のじゃまにならない程度にラベルを配置してくれるイメージ。
(ただ、処理時間は比較的長い)

R
p <- ggplot(iris,aes(x=Sepal.Length, y=Sepal.Width, color=Sepal.Width)) +
  geom_point()
direct.label(p, "smart.grid")

image.png

折れ線グラフ

R
# 描画用データ準備
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"を指定することで、折れ線の先頭にラベルを出力する。

R
p <- ggplot(df, aes(x=Year, y=Users, colour=Country)) + 
  geom_line()
directlabels::direct.label(p, method="first.qp")

image.png

ラベル位置に"last.qp"を指定することで、折れ線の末尾にラベルを出力する。

R
directlabels::direct.label(p, method="last.qp")

image.png

ラベル位置に"angled.boxes"を指定することで、折れ線の適当な位置に矩形のラベルを出力する。

R
directlabels::direct.label(p, method="angled.boxes")

image.png

等高線図

ラベル位置に"top.pieces"を指定することで、各レベルの等高線の上側にラベルを出力する。

R
p <- ggplot(faithfuld, aes(waiting, eruptions, z = density)) +
  geom_contour(aes(colour=..level..))
direct.label(p, "top.pieces")

image.png

ラベル位置に"top.pieces"を指定することで、各レベルの等高線の下側にラベルを出力する。

R
direct.label(p, "bottom.pieces")

image.png

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?