小提琴图的绘制方法有很多,像ggplot2、ggstatsplot等等众多包都可以绘制,其功能也相当丰富,感兴趣的读者可以参考:

用R快速绘制小提琴图(ggplot2版)

ggstatsplot调整颜色-科研神器

本文主要介绍除了以上两种主要R 包外的另一个小提琴绘制包vioplot,示例如下:


library(vioplot)
library(dplyr)


# 加载演示一数据
data("diamonds", package = "ggplot2")
# 颜色集
palette <- RColorBrewer::brewer.pal(9, "Pastel1")

vioplot(price ~ cut,
        data = diamonds,
        col = palette)

如果我们需要在图上添加图例,可以参考下面示例:


# 生成演示二数据
data_one <- rnorm(100)
data_two <- rnorm(50, 1, 2)

# 添加图例
vioplot(
  data_one,
  data_two,
  col = c("red", "blue"),
  names = c("data one", "data two"),
  main = "data violin",
  xlab = "data class",
  ylab = "data read"
)
legend("topleft",
       fill = c("red", "blue"),
       border = "white",
       bty = "n",
       legend = c("data one", "data two"))

参考资料:

1.https://github.com/TomKellyGenetics/vioplot