散布図の点の数が多すぎると次のような問題を感じることがある。
- 点が重なりまくる
- 描画が遅い
library(ggplot2) #ggplot2 の diamonds データを例に使う plot(price~carat, data=diamonds)
これらへの簡単な対処法として、pch="."
を指定して点を小さくするというのがある。
plot(price~carat, data=diamonds, pch=".")
点の重なりが多少改善され、描画も少し速くなる(気がする)。
プロットに多少時間がかかるのはしようがないとして、マーカーの透明度を上げるという手もある。
#rgb() の4つめの引数が不透明度 plot(price~carat, data=diamonds, col=rgb(0,0,0,0.02))
点が重なったところは色が濃くなるので頻度の情報も多少読み取りやすくなる。
この2つの合わせ技が次の図:
plot(price~carat, data=diamonds, col=rgb(0,0,0,0.1), pch=".")
ggplot2 では、透明度を上げるには次のようにする。
theme_set(theme_bw(14)) #デフォルトのグレー背景が好みでないので ggplot(diamonds, aes(carat, price, colour=cut))+ geom_point(alpha=0.1)
ついでに色分けで層別してあるが、凡例の色も薄くなってしまって見えづらいときがある。
そんな場合のために guides
関数で凡例の alpha
を上書きすることができる。
ggplot(diamonds, aes(carat, price, colour=cut))+ geom_point(alpha=0.1)+ guides(colour = guide_legend(override.aes = list(alpha = 1)))
このやり方は からっぽのしょこの id:anemptyarchive さんに教えてもらった。ありがとうございます!
ggplot(diamonds, aes(carat, price, colour=cut))+
— しょこ📚 (@anemptyarchive) 2024年2月27日
geom_point(alpha=0.1)+
guides(colour = guide_legend(override.aes = list(alpha = 1)))
でどうでしょうか pic.twitter.com/NYyALBRP9p
さらに点が多いときなどは hexbin
を使うことも多い。
ggplot(diamonds, aes(carat, price))+ geom_hex()
ビンごとに集計して度数を色の濃さ(など)で表すもの。
散布図の描画が遅いのは点の座標をデータの数だけポチポチしているからなので(だと思う)、集計してしまうと描画も速くなるし頻度も読みとりやすい。
逆にデメリットとしてはビンの幅によってデータを均しすぎたりもできるという可能性はあるかもしれない。
飛び抜けて値の大きいビンがあるとき(0が多いデータなど)は色を対数スケールにしたりすることもある。
ggplot(diamonds, aes(carat, price))+ geom_hex(aes(fill=after_stat(log2(count))))
色分けと hexbin
の合わせ技が次の図:
ggplot(diamonds, aes(carat, price, colour=cut))+ geom_hex(aes(alpha=after_stat(log2(count))), fill="darkgrey")
でも素直に facet_
で図を並べたほうが見やすいかも:
ggplot(diamonds, aes(carat, price))+ geom_hex(aes(alpha=after_stat(log2(count))), fill="darkgrey")+ facet_wrap(~cut)
以上です。