對於一個離散型變量,一個連續型變量,有很多作圖方式,包括箱圖,點圖等等
• geom_boxplot() for box plot
• geom_violin() for violin plot
• geom_dotplot() for dot plot
• geom_jitter() for stripchart
• geom_line() for line plot
• geom_bar() for bar plot
今天我們介紹一下小提琴圖
library(ggplot2)data("ToothGrowth")ToothGrowth$dose <- as.factor(ToothGrowth$dose)head(ToothGrowth)
我們先建立一個圖層,以dose為X軸,len為Y軸
e <- ggplot(ToothGrowth, aes(x = dose, y = len))主要函數及參數
• Key function: geom_violin()
• Alternative function: stat_ydensity()
• Key arguments to customize the plot: alpha, color, linetype, size and fill.e + geom_violin()e + geom_violin() + coord_flip()e + geom_violin(trim = FALSE, fill = "steelblue")
加統計值
stat_summary() 可以加均值/中位值等
用fun= mean/median加均值/中位值
e + geom_violin(trim = FALSE) + stat_summary(fun= mean, geom = "point", shape = 23, size = 2, color = "blue")
加均值及標準差
e + geom_violin(trim = FALSE) + stat_summary(fun.data="mean_sdl", fun.args = list(mult=1), geom="pointrange", color = "red")
加框,包含中位數及四分位數
e + geom_violin(trim = FALSE) + geom_boxplot(width = 0.2)
改變顏色
e + geom_violin(aes(color = dose), trim = FALSE)e + geom_violin(aes(fill = dose), trim = FALSE)
自定義顏色
e2 <- e + geom_violin(aes(color = dose), trim = FALSE) + theme_minimal()e2 + scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9"))
e3 <- e + geom_violin(aes(fill = dose), trim = FALSE) + theme_minimal()e3 + scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9"))
添加分組變量
e + geom_violin(aes(fill = supp), trim = FALSE)e + geom_violin(aes(fill = supp), trim = FALSE) + scale_fill_manual(values=c("#999999", "#E69F00"))
往期推薦:
手把手教你比較兩個模型的預測能力
手把手教你繪製生存曲線
手把手掌握臨床研究的必備繪圖技能:列線圖
手把手教你GoPlot圈圖
手把手教你繪製進階版熱圖
手把手教你學會森林圖繪製
輕輕鬆鬆繪製桑基圖
手把手教你畫雙基因生存曲線
手把手教你畫漂亮的和弦圖(上)
手把手教你畫漂亮的和弦圖(下)
手把手教你做傾向評分匹配
課程推薦
多點好看,少點脫髮