library(ggplot2)#構建數據data <- data.frame( name = c( rep("A",400), rep("B",200), rep("C",100), rep('D', 50)), value = c( rnorm(400, 10, 5), rnorm(200, 18, 1), rnorm(100, 25, 4), rnorm(50, 12, 1) ))head(data)# name value#1 A 7.7115618#2 A 8.6156297#3 A 0.2328225#4 A 3.3271746#5 A 3.6398567#6 A 14.9391309# Most basic violin chartp <- ggplot(data, aes(x = name, y = value, fill = name)) + geom_violin() + theme_bw()p
不是很好看哈(真難看…………)
注意在使用geom_violin()函數構建小提琴圖時, 數據格式為長數據 (long format). 每一行是一個觀測. 一共需要兩列:
一個分類變量, 用於 X 軸. 需要為factor格式.數值型變量, 用於 Y 軸.數據轉換如果數據為寬數據格式, 需要對其進行轉變. 可以使用tidyr中的pivot_longer()函數將其轉變為長數據格式.
data_wide <- iris[ , 1:4]head(data_wide)# Sepal.Length Sepal.Width Petal.Length Petal.Width#1 5.1 3.5 1.4 0.2#2 4.9 3.0 1.4 0.2#3 4.7 3.2 1.3 0.2#4 4.6 3.1 1.5 0.2#5 5.0 3.6 1.4 0.2#6 5.4 3.9 1.7 0.4library(tidyverse)data_long <- data_wide %>% tidyr::pivot_longer(cols = everything(), names_to = "variable", values_to = "value")head(data_long)library(ggplot2)data_long %>% ggplot(., aes(variable, value)) + geom_violin(aes(fill = variable)) + theme_bw()
橫著畫一個
library(ggplot2)library(tidyverse) iris[ , 1:4] %>% tidyr::pivot_longer(cols = everything(), names_to = "variable", values_to = "value") %>% ggplot(., aes(variable, value)) + geom_violin(aes(fill = variable, colour = variable)) + theme_bw() + theme(legend.position = "none") + coord_flip()
加點兒細節,就和封面的形式很像了
library(ggplot2)library(tidyverse) iris[ , 1:4] %>% tidyr::pivot_longer(cols = everything(), names_to = "variable", values_to = "value") %>% ggplot(., aes(variable, value)) + geom_violin(aes(fill = variable, colour = variable), width = 1.4) + geom_boxplot(fill = NA, width = 0.1, colour = "grey") + theme_bw() + theme(legend.position = "none") + coord_flip()