LoginSignup
4
3

More than 3 years have passed since last update.

Rのfacet_wrapで、個々のグラフにそれぞれのgeom_"xx"line(hline,vline,abline)を設定する

Last updated at Posted at 2019-08-21

皆さん
Rは大好きですよね。
ggplot2も大好きですよね。
facet_wrapも便利なのでよく使いますよね
こんなグラフ書いたりしますよね。

library(tidyverse)

iris_data <- iris #癖でデータフレーム化してます。
iris_data %>%
  ggplot(aes(x = Sepal.Width, y = Sepal.Length)) +
  geom_point() +
  facet_wrap(~ Species)+
  theme_bw()

image.png

これだけでも最高に便利ですが、さらにこんなことしてみたですよね

  • Sepal.Lengthの平均を表す線を、irisの種類別に組み込みたい(geom_hline)
  • Sepal.Widthの平均を表す線を、irisの種類別に組み込みたい(geom_vline)
  • irisの種類別に1次直線を引きたい(geom_abline)

今回は、それをgeom_"xx"line系列の関数を利用して組み込んでみます。

事前準備

iris_dataのデータフレームとは別に、下記のデータを用意します

dMean <- iris_data %>%
  group_by(Species) %>% #facet_wrapで指定する分類軸でgroup_by
  summarise(Sepal.Length_mean = mean(Sepal.Length),
            Sepal.Width_mean = mean(Sepal.Width))

Speciesの名前を残すことが大事です。(後述)
これを利用して組み込んでいきます

geom_hline

iris_data %>%
  ggplot(aes(x = Sepal.Width, y = Sepal.Length)) +
  geom_point() +
  geom_hline(data = dMean, aes(yintercept = Sepal.Length_mean)) +
  facet_wrap(~ Species)+
  theme_bw()

image.png
geom_hlineの引数にdataとして先程作成したdMeanを入れることで、SpeciesごとのSepal.Lengthの平均をグラフに入れることができます。
この後も基本的に同様の流れです。

geom_vline

iris_data %>%
  ggplot(aes(x = Sepal.Width, y = Sepal.Length)) +
  geom_point() +
  geom_vline(data = dMean, aes(xintercept = Sepal.Width_mean)) +
  facet_wrap(~ Species)+
  theme_bw()

image.png

geom_abline

iris_data %>%
  ggplot(aes(x = Sepal.Width, y = Sepal.Length)) +
  geom_point() +
  geom_abline(data = dMean, aes(slope = Sepal.Length_mean, intercept = Sepal.Width_mean)) +
  xlim(0,10) + #ablineがグラフに入るように軸の幅設定
  ylim(0,10) + #ablineがグラフに入るように軸の幅設定
  facet_wrap(~ Species)+
  theme_bw()

image.png1

ちなみにdMeanSpeciesを入れないと下記のようなグラフになります。

dMean <- iris_data %>%
  group_by(Species) %>%
  summarise(Sepal.Length_mean = mean(Sepal.Length),
            Sepal.Width_mean = mean(Sepal.Width)) %>%
  select(-Species) #説明のためにSpecies列削除

iris_data %>%
  ggplot(aes(x = Sepal.Width, y = Sepal.Length)) +
  geom_point() +
  geom_hline(data = dMean, aes(yintercept = Sepal.Length_mean)) +
  facet_wrap(~ Species)+
  theme_bw()

image.png

setosa,versicolor,virginiaそれぞれのSepal.Lengthの平均が組み込まれてしまいます。
これは推測ですが、facet_wrapでの分類軸と照らし合わせる必要がありそうです。

Enjoy!


  1. このグラフを作る実際的な意味はありませんが、説明用で作りました 

4
3
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
4
3