空飛ぶチンアナゴの統計解析日記

統計解析を嗜むチンアナゴのメモ帳です

1.8 練習問題の回答と解説

注意書き
当該記事には「Rではじめるデータサイエンス」のネタバレを多数含みます。
自分で回答することが一番の力になりますのでなるべく自力で回答するようよろしくお願いいたします。

1. このプロットの問題は何か。どうすれば改善できるか。

ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) + 
  geom_point()


典型的なオーバープロットなのでgeom_point()にposition = "jitter"を追加することで、オーバープロットを回避することができます。

ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) + 
  geom_point(position = "jitter")


最初のグラフに比べて原点付近の方に点が固まっていることがよくわかるかと思います。

2. geom_jitter()のどの引数がジッターの量を制御するか。

width
Amount of vertical and horizontal jitter. The jitter is added in both positive and negative directions, so the total spread is twice the value specified here.
If omitted, defaults to 40% of the resolution of the data: this means the jitter values will occupy 80% of the implied bins. Categorical data is aligned on the integers, so a width or height of 0.5 will spread the data so it's not possible to see the distinction between the categories.
height
Amount of vertical and horizontal jitter. The jitter is added in both positive and negative directions, so the total spread is twice the value specified here.
If omitted, defaults to 40% of the resolution of the data: this means the jitter values will occupy 80% of the implied bins. Categorical data is aligned on the integers, so a width or height of 0.5 will spread the data so it's not possible to see the distinction between the categories.

と公式ドキュメントにあるようにwidthheightです。

3. geom_jitter()とgeom_count()を比較対照しなさい

一番の違いは引数positionの違いではないでしょうか?
geom_jitter()のpositionはデフォルトで"jitter"ですが、geom_count()のpositionはデフォルトでは"identity"となっています。
jitterをかけることを考えるのであれば最初からgeom_jitter()関数を使った方がいいですね。

4. geom_boxplot()のデフォルトの位置調整は何か。それを示すmpgデータセットの可視化を作りなさい。

公式ドキュメントを確認するとデフォルトのpositionは"dodge2"と呼ばれるpositionです。
dodgeと呼ばれるpositionについては
ggplot2.tidyverse.org
を参考にすると良いでしょう。
実際にx軸を気筒数、y軸を高速道路の燃費としてグラフを作成してみると

ggplot(data = mpg, 
       mapping = aes(x= cyl, y = hwy, group=cyl)
       ) +
  geom_boxplot()


のようになります。