自分の勉強がてらに神Hadley R for Data Science の例題たちとその解答を書き残します。
まずはChapter 3から。
この章ではライブラリggplot2
を使う。
library(ggplot2)
3. Data visualization
3.2. First Steps
3.2.4. Exercises
1. Run
ggplot(data = mpg)
. What do you see?
新規のプロットがブランクで開く。
2. How many rows are in
mpg
? How many columns?
ncol(mpg); nrow(mpg) #[1] 11 #[1] 234
3. What does the
drv
variable describe? Read the help for?mpg
to find out.
値はf, r, 4
の三種類を取り、それぞれフロントドライブ、リアドライブ、4WDを意味している
4. Make a scatterplot of
hwy
vscyl
.
ggplot(mpg, aes(hwy, cyl)) + geom_point()
5. What happens if you make a scatterplot of
class
vsdrv
? Why is the plot not useful?
ggplot(mpg, aes(class, drv)) + geom_point()
縦軸も横軸も離散型なので散布図の点が重なってしまう。
どれだけデータがあるのかが全く見えない。
3.3. Aesthetic mappings
3.3.1. Exercises
1. What’s gone wrong with this code? Why are the points not blue?
ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy, color = "blue"))
“blue”という文字列だけが並ぶフィールドに色が割り当てられているため。
フィールドの値ではなく色を”blue”に割り当てたければ次のようにする。
ggplot(data =mpg) + geom_point(mapping = aes(x = displ, y = hwy), color = "blue")
2. Which variables in
mpg
are categorical? Which variables are continuous? (Hint: type?mpg
to read the documentation for the dataset). How can you see this information when you runmpg
?
カテゴリ変数は、manufacturer, model, year, cyl, trans, drv, fl, class
連続変数は displ, year, cty, hwy
year
は連続ではないが差の計算ができる間隔尺度。
一方cyl
は差の計算に意味がなく大小関係のみに意味がある順序変数
3. Map a continuous variable to
color
,size
, andshape
. How do these aesthetics behave differently for categorical vs. continuous variables?
color
は連続的な色の変化で表現される。
size
は連続的な大きさの変化で表現される。
shape
に連続変数を設定するとエラーを返す。連続変数を当てはめることはできない。
4. What happens if you map the same variable to multiple aesthetics?
割り当てたaestheticsそれぞれに正しく適用される。
5. What does the stroke aesthetic do? What shapes does it work with? (Hint: use
?geom_point
)
strokeは散布図の点の枠線の太さを指定する。
geom_pointのhelpではshape = 21とする例がある。デフォルトのshapeでは塗りつぶされていて枠線の太さの区別ができない。
shape = 0,1,2などでもいける。
6. What happens if you map an aesthetic to something other than a variable name, like
aes(colour = displ < 5)
?
式を評価した結果がaestheticに適用される。
この例ではdispl < 5
という論理ベクトルで二つに色分けされる。
3.5. Facets
3.5.1. Exercise
1. What happens if you facet on a continuous variable?
連続値のそれぞれの値に対してfacetができる。
つまりたくさんのfacetができる。
2. What do the empty cells in plot with
facet_grid(drv ~ cyl)
mean? How do they relate to this plot?ggplot(data = mpg) + geom_point(mapping = aes(x = drv, y = cyl))
facet_grid
の組み合わせでデータが無い場合は、軸だけでデータが無いグラフが表示される。
aes(x = drv, y = cyl)
のプロットで各drv
, cyl
にデータが存在しているかどうかを確認することができる。
3. What plots does the following code make? What does
.
do?ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy)) + facet_grid(drv ~ .) ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy)) + facet_grid(. ~ cyl)
facet_grid(drv ~.)
のプロットはdrv
ごとに縦にグラフが並ぶ。
facet_grid(. ~ cyl)
のプロットはcyl
ごとに横にグラフが並ぶ。
ピリオドは指定なしの意味。ただし下のfacet_grid(. ~ cyl)
はピリオド無しでもプロットできる。
4. Take the first faceted plot in this section:
ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy)) + facet_wrap(~ class, nrow = 2)What are the advantages to using faceting instead of the colour aesthetic? What are the disadvantages? How might the balance change if you had a larger dataset?
color aestheticでは重なったデータが重なった場合にはパターンを見出しづらい。データが密集している場合はfacetでデータを分割して見る効果は大きい。
facetの欠点は1つのグラフが小さくなってしまうこと。系列の種類数が多い場合はfacetで分析するのは難しい。
また連続値にも対応できない。
5. Read
?facet_wrap
. What doesnrow
do? What doesncol
do? What other options control the layout of the individual panels? Why doesn’tfacet_grid()
havenrow
andncol
argument?
nrow
を指定するとfacet_wrap
で配置されるグラフの行数をしていできる。たとえば nrow = 1
だと横一列に並ぶ。
同様にncol
を指定すると列数の指定になる。
dir
オプションはチャートを並べる順番を指定する。dir = "v"
とすると、グラフを縦向きに配置していく。
facet_grid
は指定する変数の種類数がnrow
, ncol
になるのでオプションで制御することはできない。
6. When using
facet_grid()
you should usually put the variable with more unique levels in the columns. Why?
通常ディスプレイは横長だから。
3.6. Geometric objects
3.6.1. Exercise
1. What geom would you use to draw a line chart? A boxplot? A histogram? An area chart?
line chartはgeom_line
, boxplotはgeom_boxplot
, histogramはgeom_histogram
, area chartはgeom_area
2. Run this code in your head and predict what the output will look like. Then, run the code in R and check your predictions.
ggplot(data = mpg, mapping = aes(x = displ, y = hwy, color = drv)) + geom_point() + geom_smooth(se = FALSE)
3. What does
show.legend = FALSE
do? What happens if you remove it?
Why do you think I used it earlier in the chapter?
show.legend = FALSE
で右側の凡例がなくなる。
show.legend = FALSE
としたのはデフォルトで凡例が無いグラフと大きさを一致させることができるため。
4. What does the
se
argument togeom_smooth()
do?
Standard Errorの略で、信頼区間を表示するかどうかを指定する。
level
オプションで信頼区間の設定値を変更できる。(デフォルトは0.95)
5. Will these two graphs look different? Why/why not?
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) + geom_point() + geom_smooth() ggplot() + geom_point(data = mpg, mapping = aes(x = displ, y = hwy)) + geom_smooth(data = mpg, mapping = aes(x = displ, y = hwy))
全く同じ。
6. Recreate the R code necessary to generate the following graphs.
gp <- ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) gp + geom_point() + geom_smooth(se = FALSE) gp + geom_point() + geom_smooth(aes(group = drv), se = FALSE) gp + geom_point(aes(color = drv)) + geom_smooth(aes(color = drv), se = FALSE)) gp + geom_point(aes(color = drv)) + geom_smooth(se = FALSE) gp + geom_point(aes(color = drv)) + geom_smooth(aes(color = drv, linetype = drv), se = FALSE) gp + geom_point(aes(fill = drv), shape = 21, color = "white", stroke = 1)
3.7 Statistical transformations
3.7.1. Exercises
1. What is the default geom associated with
stat_summary()
? How could you rewrite the previous plot to use that geom function instead of the stat function?
stat_summary
のデフォルトのgeomはpointrange
。
geomに置き換えるためには下記のようにする。
ggplot(diamonds) + geom_pointrange(aes(cut, depth), stat = "summary", fun.y = median, fun.ymin = min, fun.ymax = max)
2. What does
geom_col()
do? How is it different togeom_bar()
?
geom_bar
はデフォルトのstatがcount
なのに対して、geom_col
はidentity
。
よってgeom_col
はaes
でy
の変数も指定する。
3. Most geoms and stats come in pairs that are almost always used in concert. Read through the documentation and make a list of all the pairs. What do they have in common?
color
, size
, fill
などは全てのプロットで共通
geom | stat | 共通で持つ設定 |
---|---|---|
geom_bar | stat_count | width, position |
geom_point | stat_identity | position |
geom_histogram | stat_bin | position, binwidth, bins |
geom_density | stat_density | position |
geom_boxplot | stat_boxplot | position |
geom_count | stat_sum | position |
など
4. What variables does
stat_smooth()
compute? What parameters control its behaviour?
methodsでstat_smooth
が計算する予測曲線の計算方法を決定する。
デフォルトは局所線形回帰(LOESS)。
5. In our proportion bar chart, we need to set
group = 1
. Why? In other words what is the problem with these two graphs?ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut, y = ..prop..)) ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut, fill = color, y = ..prop..))
上記のコードのままだと、..prop..
で比率の計算がcut
ごとに計算されるため、すべての行で1.00が表示される。
group = 1
と設定することで全体の1つのグループとして比率の計算をするようにする。
3.8. Position Adjustment
3.8.1. Exercises
1. What is the problem with this plot? How could you improve it?
ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) + geom_point()
cty
, hwy
ともに取りうる値の種類数が少ないので、散布図の点が重なってしまってどれだけ散布しているのかが分からない。
geom_point
にposition = "jitter"
オプションを追加すれば見えるようになる。
position = "jitter"
の代わりに、stat = "sum"
を指定すれば点の大きさでデータ数が分かるようになる。
2. What parameters to
geom_jitter()
control the amount of jittering?
width
で横側のjittering、height
で縦側のjitteringを設定できる。
設定値0でjitteringなし、デフォルトは0.4。
3. Compare and contrast
geom_jitter()
withgeom_count()
.
geom_jitter
はデータの多少を点がどれだけ密集しているかどうかの見た目で評価する。密度が高いエリアを見出すのに使える。
geom_count
ではそれぞれの点で左右と比較して多いかどうかを比較することができる。あくまで点の評価であり、エリアで評価するのには向いていない。
4. What’s the default position adjustment for
geom_boxplot()
? Create a visualisation of thempg
dataset that demonstrates it.
ggplot(diamonds, aes(clarity, price)) + geom_boxplot(aes(color = color))
3.9. Coordinate systems
3.9.1 Exercises
1. Turn a stacked bar chart into a pie chart using
coord_polar()
.
ggplot(diamonds, aes(cut)) + geom_bar(aes(fill = color)) + coord_polar()
2. What does
labs()
do? Read the documentation.
labs(x = "x labs", y = "y labs")
でx軸とy軸のラベルを指定できる。
3. What’s the difference between
coord_quickmap()
andcoord_map()
?
三次元球面座標を二次元座標に置き換える際にcoor_map
は厳密に計算(デフォルトではメルカトル図法)するのに対して、coor_quickmap
は近似計算を行う。
4. What does the plot below tell you about the relationship between city and highway mpg? Why is
coord_fixed()
important? What doesgeom_abline()
do?ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) + geom_point() + geom_abline() + coord_fixed()
cty
が高い方がcty
とhwy
との差が広がる傾向がある。
coord_fixed
は軸のスケールを縦横で合わせて固定する。この固定がなければウィンドウの大きさによってスケールが変わってしまい、傾向を見出す際にミスリードを生じる可能性がある。
geom_abline()
はy=xの直線を引くが、coord_fixed
を設定していることで、y=xの直線が正確に45度の角度になる。