用ggplot2繪制小提琴圖+箱形圖

本文記錄了:
小提琴圖+箱形圖的繪制,箱形圖放置小提琴圖內(nèi)部,并進行顯著性差異檢驗。

成圖如下所示:

加載所需要的包

library(ggplot2)
library(ggpubr)
library(ggsci)
library(ggsignif)

查看示例數(shù)據(jù)

str(iris)
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

table(iris$Species)
    setosa versicolor  virginica 
        50         50         50 

成圖

ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species)) +
  geom_violin(trim = FALSE, alpha = 0.5) +
  geom_boxplot(
    width = 0.1, # 箱子寬度,使其能縮進在小提琴里
    fill = "white",
    outlier.shape = 0 # 將離群點畫為一個小方塊,要隱藏則設置為NA
  ) +
  # 添加誤差線
  stat_boxplot(
    geom = "errorbar",
    position = position_dodge(width = 0.1),
    width = 0.1
  ) +
  # 添加散點
  geom_jitter(
    width = 0.2, alpha = 0.3
  )+
  # ggpubr
  theme_pubr() + # 主題先設置,不然會覆蓋后續(xù)的微調(diào)。
  labs(
    title = "Violin Plot with Boxplot",
    subtitle = "Fisher's Iris Data",
    x = "Species",
    y = "Sepal Length",
    caption = "Statistics: Pairwise Wilcoxon rank sum test; *** p < 0.001"
  ) +
  theme(                     
    axis.text.x = element_text(angle = 45, hjust = 1),
    legend.title = element_blank()
  )+
  # ggsci
  scale_fill_manual(
    values = ggsci::pal_aaas()(3)
  ) +
  # ggsignif
  geom_signif(
    test = "wilcox.test", # default.
    comparisons = list(
      c("setosa", "versicolor"), # 設置誰與誰比較
      c("setosa", "virginica"),
      c("versicolor", "virginica")
      ),
    step_increase = 0.1, # 當有多個對比線時,每根線向上錯開 10%,防止重疊
    map_signif_level = FALSE # 設置為F(default),表示直接顯示具體的 P 值數(shù)值,而不是星號(***)
  )
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • """1.個性化消息: 將用戶的姓名存到一個變量中,并向該用戶顯示一條消息。顯示的消息應非常簡單,如“Hello ...
    她即我命閱讀 4,915評論 0 6
  • 1、expected an indented block 冒號后面是要寫上一定的內(nèi)容的(新手容易遺忘這一點); 縮...
    庵下桃花仙閱讀 1,068評論 1 2
  • 一、工具箱(多種工具共用一個快捷鍵的可同時按【Shift】加此快捷鍵選取)矩形、橢圓選框工具 【M】移動工具 【V...
    墨雅丫閱讀 1,467評論 0 0
  • 跟隨樊老師和伙伴們一起學習心理知識提升自已,已經(jīng)有三個月有余了,這一段時間因為天氣的原因休課,順便整理一下之前學習...
    學習思考行動閱讀 937評論 0 2
  • 一臉憤怒的她躺在了床上,好幾次甩開了他抱過來的雙手,到最后還堅決的翻了個身,只留給他一個冷漠的背影。 多次嘗試抱她...
    海邊的藍兔子閱讀 961評論 1 4

友情鏈接更多精彩內(nèi)容