Yoshi Nishikawa Blog

医学となにかのインタラクティブ

ggplot2でグラフ作成 (2)

ggplot2

2016年に出版されたggplot2に関するHadley Wickhamによる著書。その名もggplot2、の続き。

コンテンツ

大きく分けて3部で構成され、全12章にわかれている。今回は第2回。

Part2 文法

4 文法

文法が大切である。

5 レイヤー

データ、aes、stat、geom、位置決めで出来ている。
geomの使い方は役に立つ

geom_smooth()  
geom_boxplot()  
geom_histogram()   
geom_freqpoly()  
geom_bar()  
geom_path()  
geom_line()  

ここも参考に

6 スケール、軸、レジェンド

図を書くときの、scale, axis, legendに関する各設定。

p<-ggplot(mpg,aes(cty,hwy))+
  geom_abline()+
  geom_jitter(width=0.1,height=0.1)
p+facet_wrap(~cyl) #scale設定無いとそれぞれ同じ軸で見ている。
p+facet_wrap(~cyl, scales = "free") #scalesをfreeに設定するといい感じにバラける。

f:id:yoshi_nishikawa:20161008173333p:plainf:id:yoshi_nishikawa:20161008173334p:plain

7 位置決め

dplyrとも互換性よい。facet分けして、背景はグレー、分けられた群は色付き、ということが出来る。

df<-data.frame(x=rnorm(120, c(0,2,4)),y=rnorm(120,c(0,2,1)),z=letters[1:3])
p<-ggplot(df, aes(x,y))+geom_point(aes(colour=z))
p

df2<-dplyr::select(df,-z)
ggplot(df,aes(x,y))+
  geom_point(data=df2,colour="grey70")+
  geom_point(aes(colour=z))+
  facet_wrap(~z)

f:id:yoshi_nishikawa:20161008172940p:plain f:id:yoshi_nishikawa:20161008172937p:plain

8 テーマ

7つ(+デフォルト)のテーマがある。それぞれ、試してみる。添付画像は、gray, void, bw, darkだ。ggthemesというパッケージもある・・・!

df<-data.frame(x=rnorm(120, c(0,2,4)),y=rnorm(120,c(0,4,2)),z=letters[1:3])
p<-ggplot(df,aes(x,y))+geom_point(aes(colour=z))
p+theme_gray()+ggtitle("theme_gray")
p+theme_bw()+ggtitle("theme_bw")
p+theme_linedraw()+ggtitle("theme_linedraw")
p+theme_light()+ggtitle("theme_light")
p+theme_dark()+ggtitle("theme_dark")
p+theme_minimal()+ggtitle("theme_minimal")
p+theme_classic()+ggtitle("theme_classic")
p+theme_void()+ggtitle("theme_void")

library(ggthemes)
p+theme_wsj()+ggtitle("theme_wsj")
p+theme_economist()+ggtitle("theme_economist")

f:id:yoshi_nishikawa:20161008172005p:plainf:id:yoshi_nishikawa:20161008171748p:plainf:id:yoshi_nishikawa:20161008171750p:plainf:id:yoshi_nishikawa:20161008171758p:plain f:id:yoshi_nishikawa:20161008174422p:plainf:id:yoshi_nishikawa:20161008174425p:plain

残る箇所はまた今度。

Part3 データ解析
9 データ解析
10 データ変換
11 可視化のためのモデリング
12 プログラミング

1つ古い版の日本語の訳本はこちら。