Radi_tech’s blog

Radiological technologist in Japan / MRI / AI / Deep learning / MATLAB / R / Python

【R】箱ひげ図に各データをドットプロットする

R boxplot
R boxplot

最近は、箱ひげ図にデータをドットプロットするのを求められるようです。
定番の"iris"データを使って練習

ちなみにドットプロットは蜂群図というらしい

過去記事はこちら
radi-tech.hatenablog.com

help(iris)  #description of iris data

dat <- iris # import iris data
attach(dat)

library(dplyr)
library(psych)

# show overall summary
describeBy(iris,Species)
# show only length of each species
describeBy(Sepal.Length ,Species)



###################################
#library for plot

library(ggplot2)
library(ggsignif)
library(gridExtra)
library(ggpubr)
library(rstatix)

p_length <- ggplot(dat , mapping = aes(x = Species, y = Sepal.Length))
p_length <- p_length + geom_boxplot(fill = "lightblue")
p_length 

p_length <- p_length + geom_signif(comparisons = list(c("setosa", "versicolor")), 
                                   map_signif_level=TRUE,
                                   y_position = 7,
                                   annotation="** p<0.001",
                                   fontface="italic", 
                                   textsize=10)

p_length <- p_length + geom_signif(comparisons = list(c("virginica", "versicolor")), 
                                   map_signif_level=TRUE,
                                   y_position = 8,
                                   annotation="** p<0.001",
                                   fontface="italic", 
                                   textsize=10)

p_length <- p_length + geom_signif(comparisons = list(c("setosa", "virginica")), 
                                   map_signif_level=TRUE,
                                   y_position = 8.8,
                                   annotation="** p<0.001",
                                   fontface="italic", 
                                   textsize=10)
# adjusting of y lim
p_length <- p_length + ylim(2,10)
# change to white back groud
p_length <- p_length + theme_classic()
# adjusting of aspect ratio
p_length <- p_length + theme(aspect.ratio=1) 
# adjusting of aspect ratio
p_length <- p_length + theme(text = element_text(size = 30))

p_length

###dot plot

install.packages("ggbeeswarm")  #if you don't have installed package
library(tidyverse)
library(ggbeeswarm)

p_length_bees <- p_length + geom_beeswarm(aes(color = Species))
p_length_bees


p_length_dot <- p_length + geom_point(position = position_jitter(width=0.05))
p_length_dot 

最後のところが重要
geom_beeswarmを使うとこんな感じ

install.packages("ggbeeswarm")  #if you don't have installed package
library(tidyverse)
library(ggbeeswarm)

p_length_bees <- p_length + geom_beeswarm(aes(color = Species))
p_length_bees
R boxplot ドットプロット
R boxplot ドットプロット
p_length_dot <- p_length + geom_point(position = position_jitter(width=0.05))
p_length_dot 
R boxplot ドットプロット
R boxplot ドットプロット