LoginSignup
2

More than 3 years have passed since last update.

ggplot::geom_flat_violinのススメ

Last updated at Posted at 2020-09-07

はじめに

私はdgrtwo氏の作ったggplot2用のgeom_flat_violin.Rがお気に入りで、よく使わせていただいています。
しかし、このプロットを取り挙げて下さっていたはてなブログの記事がいつのまにやら消えており、悲しかったので簡単に使用法をまとめてみました。

準備

残念なことに、スクリプトには余計な" ) "が含まれているので一度こちらからダウンロードし、50行目にある" ) "を消去しておいてください。

以下のコードを実行すると不要な)についてエラーメッセージを確認できます。

library(devtools)

source_url("https://gist.githubusercontent.com/dgrtwo/eb7750e74997891d7c20/raw/ed346ccc73cfffcc9e9f1ca51281bb078f4d48a6/geom_flat_violin.R")

> source_url("https://gist.githubusercontent.com/dgrtwo/eb7750e74997891d7c20/raw/ed346ccc73cfffcc9e9f1ca51281bb078f4d48a6/geom_flat_violin.R")
SHA-1 hash of file is 5763fa02179f37bc448799e51370cb07290ea09a
 source(temp_file, ...) でエラー: 
  /var/folders/4s/z0ll_w5s007fvk07vs41w6yh0000gn/T//RtmpMtIvAM/file1e61517c6333:50:13:  予想外の ')' です 
49:                      xmax = x + width / 2)
50:             )
                ^

編集したスクリプトは適当な名前(例えばgeom_flat_violin.R)で保存し、ワーキングディレクトリに置いておきます。

導入

ggplot2と先程のスクリプトを読み込みます

library(ggplot2)
source("geom_flat_violin.R")

使用例

おなじみのirisです

p<-ggplot(NULL)
p<-p+geom_flat_violin(data=iris,mapping = aes(x=Species,y=Sepal.Length,fill=Species),scale="count",trim=FALSE)+
  ggtitle("Sepal.Length")
p<-p+geom_dotplot(data=iris,mapping=aes(x=Species,y=Sepal.Length,fill=Species),binaxis = "y",dotsize = 1,stackdir = "down",binwidth = 0.1,position = position_nudge(x=-0.025))
p

flat_violin_exp.png

geom_dotplotとの組み合わせにより、値の分布が非常に分かりやすくなりました。
position_nudgeを駆使すれば平均値や標準偏差を導入することもできます。

下の箱ひげ図と比べると見やすさが段違いです。

p<-ggplot(NULL)
p<-p+geom_boxplot(data=iris,mapping=aes(x=Species,y=Sepal.Length,fill=Species))
p

geom_box_exp.png

さいごに

私はgeom_flat_violinを知る以前、箱ひげ図を多用していました。
しかしながら、年齢層が上の方は数学で箱ひげ図を習っていない場合があるそうです。
箱ひげ図って事前知識なしに理解するのは難しいですよね。
その点こいつは直感で理解できる破壊力があります。
ぜひ活用してみてください。enjoy!!

参考

jbburant氏のプロット作図例
https://gist.github.com/jbburant/b3bd4961f3f5b03aeb542ed33a8fe062

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2