外部記憶装置

ggplot2::layer()で凡例付きのグラフを描く

はじめに

複数のデータを1つのグラフにまとめて表現する際に ggplot2::layer() をよく使っている。 1つのグラフにまとめる以上、どの表現がどのデータの傾向を示しているのか見て取れるように凡例が必要になる。

環境

使用するライブラリーとデータは次の通り

require(dplyr)
require(ggplot2)

data(iris)
setosa_df <- iris %>% filter(Species == "setosa") %>% select(-Species)
versicolor_df <- iris %>% filter(Species == "versicolor") %>% select(-Species)
virginica_df <- iris %>% filter(Species == "virginica") %>% select(-Species)

凡例なしの場合

ggplot() +
  layer(
    data = setosa_df,
    geom = "point",
    mapping = aes(x = Sepal.Length, y = Sepal.Width),
    stat = "identity",
    position = "identity",
    params = list(color = "red", alpha = 0.7)
  ) +
  layer(
    data = versicolor_df,
    geom = "point",
    mapping = aes(x = Sepal.Length, y = Sepal.Width),
    stat = "identity",
    position = "identity",
    params = list(color = "green", alpha = 0.7)
  ) +
  layer(
    data = virginica_df,
    geom = "point",
    mapping = aes(x = Sepal.Length, y = Sepal.Width),
    stat = "identity",
    position = "identity",
    params = list(color = "blue", alpha = 0.7)
  ) +
  theme_bw()

f:id:tai42:20200524001816p:plain
凡例なしグラフ_20200524

凡例ありの場合

mapping にてcolor = "凡例名" を加えることで凡例にそのレイヤーの可視化が紐づくみたいです。

ggplot() +
  layer(
    data = setosa_df,
    geom = "point",
    mapping = aes(x = Sepal.Length, y = Sepal.Width, color = "setosa"),
    stat = "identity",
    position = "identity",
    params = list(alpha = 0.7)
  ) +
  layer(
    data = versicolor_df,
    geom = "point",
    mapping = aes(x = Sepal.Length, y = Sepal.Width, color = "versicolor"),
    stat = "identity",
    position = "identity",
    params = list(alpha = 0.7)
  ) +
  layer(
    data = virginica_df,
    geom = "point",
    mapping = aes(x = Sepal.Length, y = Sepal.Width, color = "virginica"),
    stat = "identity",
    position = "identity",
    params = list(alpha = 0.7)
  ) +
  theme_bw() +
  scale_color_manual(
    values = c("setosa" = "red", "versicolor" = "green", "virginica" = "blue")
  ) +
  labs(color = "Species")

f:id:tai42:20200524001906p:plain
凡例ありグラフ_20200524