ggplot2覚書② 散布図
以下をベースに覚え書く。

Rグラフィックスクックブック ―ggplot2によるグラフ作成のレシピ集
- 作者:Winston Chang
- 発売日: 2013/11/30
- メディア: 大型本
前回のは以下
散布図
テキストをつける
aesでマッピングされた位置にlabelでテキストを付与。vjustでy軸位置、hjustでx軸位置を指定(デフォルト0は真上)
library(gcookbook) # データセットの読み込み library(dplyr) data <- subset(countries, Year==2009 & healthexp>2000) data %>% ggplot(aes(x=healthexp, y=infmortality)) + geom_point() + geom_text(aes(label=Name), size=4, vjust = -0.5, hjust = 0.5)
一部のみ表示したい場合は、表示したくないlabelをNAにする。
data %>% mutate(Name_filtered = if_else(Name %in% c("United Kingdom", "United States", "Japan"), Name,as.factor(NA))) %>% # リストにある場合はそのままName,ない場合はNAを返す ggplot(aes(x=healthexp, y=infmortality)) + geom_point() + geom_text(aes(label=Name_filtered), size=4, vjust = -0.5, hjust = 0.5)
いい感じの大きさにバルーンプロット
数字の大きさに応じてgeom_pointの点を大きくしたい。
sizeに数値をmappingするとできるといえばできるが、mappingした大きさに依存する。
library(gcookbook) # データセットの読み込み cdat <- subset(countries, Year==2009 & Name %in% c("Canada", "Ireland", "United Kingdom", "United States", "New Zealand", "Iceland", "Japan", "Luxembourg", "Netherlands", "Switzerland")) p <- ggplot(cdat, aes(x=healthexp, y=infmortality, size=GDP)) + geom_point(shape=21, colour="black", fill="cornsilk") # GDPを半径にマッピングする(デフォルトはscale_size_continuous) p
scale_size_area関数を用いると、指定した最大サイズを基準としてmappingした値に比例して円の大きさを変えてくれる。
p + scale_size_area(max_size=15)