LoginSignup
10
14

More than 5 years have passed since last update.

ggplot2で複数系列の折れ線グラフにラベルを付ける

Last updated at Posted at 2017-04-30

系列が沢山ある折れ線グラフをそのままプロットすると凡例との対応が分かりにくくなる。

library(ggplot2)
ggplot(CO2, aes(x = conc, y = uptake, color = Plant)) +
  geom_line()

Rplot01.png

geom_text()を使う

ggplot(CO2, aes(x = conc, y = uptake, color = Plant)) +
  geom_line() +
  geom_text(
    data = subset(CO2, conc == max(conc)),
    aes(label = Plant),
    nudge_x = 50
  ) +
  theme(legend.position = "none")

Rplot.png

subsetでx軸右端のデータを抽出し、nudge_xで少しプロット位置をずらすのとtheme(legend.position = "none")で凡例を消しておくのがポイント。ただしこの方法だとテキスト同士は重なる可能性がある。

geom_text_repel()を使う

library(ggrepel)

ggplot(CO2, aes(x = conc, y = uptake, color = Plant)) +
  geom_line() +
  geom_text_repel(
    data = subset(CO2, conc == max(conc)),
    aes(label = Plant),
    nudge_x = 100,
    segment.alpha = 0.5,
    size = 3
  ) +
  lims(x = c(min(CO2$conc), max(CO2$conc)*1.1)) +
  theme(legend.position = "none")

Rplot02.png

{ggrepel}パッケージのgeom_text_repel()はテキストが重ならないように自動的に調整してくれる。

geom_text_repel()はほぼgeom_text()と同じように使えるように作られているが、注意点がいくつかある。

  • nudge_xでプロット位置を元のプロット範囲外までずらしても、プロット範囲が自動的に拡張されない。
    • 従って、lims()でx軸のプロット範囲を拡張しておく必要がある。
  • segment(テキストから伸びる線)がデフォルトではgeom_line()の線と区別できないので、折れ線グラフの一部とみなされてしまう危険性がある。
    • 従って、segment.alpha=segment.size=arrow=等で外観を変えておいた方が良い。

余談

この内容はこの図が描きたくて調べた。

スクリーンショット 2017-05-01 2.14.14.png

が、割とどうでもいい部分で話が長くなるのでこの図の説明は有機質資材からの窒素放出量を予測したい - もうカツ丼はいいよなに書いた。

10
14
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
10
14