圖數據可視化——R語言ggplot2包和tidybayes包繪製小提琴圖進階
概述:繪製小提琴圖時按數據分佈的密度填充不同透明度的顏色(漸變填充)。
使用工具:R語言中的ggplot2和tidybayes工具包
本文使用的數據及計算方式與之前的博文一致:數據可視化——R語言ggplot2包繪製精美的小提琴圖(並箱線圖或誤差條圖組合)。
本文采用tidybayes包中stat_eye()繪製小提琴圖,通過設置aes(alpha = stat(f)可實現漸變填充。由於stat_eye()會默認採用中位數及分位數作爲誤差條,本文采用均值±標準差的形式呈現誤差條,因此屏蔽了stat_eye()默認的誤差條顯示:設置show_interval = FALSE。與前文一致,本文也用tidybayes包繪製分半的小提琴圖,並漸變填充。
小提琴圖結合誤差條圖用於表達數據的代碼如下:
rm(list=ls()) #清除工作區
library(ggplot2)
set.seed(1234)
#生成模擬數據
Group <- rep(c("group1","group2"),each=200) #組別變量
Group <- factor(Group) #組別因子化
Attribute <- c(rep("Attribute_1",100),rep("Attribute_2",100),rep("Attribute_1",100),rep("Attribute_2",100)) #每個組別的兩個屬性
Attribute <- factor(Attribute) #屬性因子化
value <- c(rnorm(100)+1,rnorm(100)+2,rnorm(100)+1.2,rnorm(100)+1.5) #隨機賦值
Data <- data.frame(Group=Group,Attribute=Attribute,value=value) #生成數據框
#對數據進行統計的函數
#指定分組變量和求值變量後,可計算出不同分組變量(或分組變量間的組合)對應的求值變量的均值,標準差,標準誤,置信區間ci
#彙總數據
#計算出計數,平均值,標準差,均值的標準誤差和置信區間(默認爲95%)
#data:一個數據框
#measurevar:包含要彙總的變量的列的名稱
#groupvars:包含分組變量的列名稱的向量
#na.rm:一個布爾值,表示是否忽略NA
## conf.interval:置信區間的百分比範圍(默認爲95%)
## Summarizes data.
## Gives count, mean, standard deviation, standard error of the mean, and confidence interval (default 95%).
## data: a data frame.
## measurevar: the name of a column that contains the variable to be summariezed
## groupvars: a vector containing names of columns that contain grouping variables
## na.rm: a boolean that indicates whether to ignore NA's
## conf.interval: the percent range of the confidence interval (default is 95%)
summarySE <- function(data=NULL, measurevar, groupvars=NULL, na.rm=FALSE,
conf.interval=.95, .drop=TRUE) {
library(plyr)
# New version of length which can handle NA's: if na.rm==T, don't count them
length2 <- function (x, na.rm=FALSE) {
if (na.rm) sum(!is.na(x))
else length(x)
}
# This does the summary. For each group's data frame, return a vector with
# N, mean, and sd
datac <- ddply(data, groupvars, .drop=.drop,
.fun = function(xx, col) {
c(N = length2(xx[[col]], na.rm=na.rm),
mean = mean (xx[[col]], na.rm=na.rm),
sd = sd (xx[[col]], na.rm=na.rm)
)
},
measurevar
)
# Rename the "mean" column
datac <- rename(datac, c("mean" = measurevar))
datac$se <- datac$sd / sqrt(datac$N) # Calculate standard error of the mean
# Confidence interval multiplier for standard error
# Calculate t-statistic for confidence interval:
# e.g., if conf.interval is .95, use .975 (above/below), and use df=N-1
ciMult <- qt(conf.interval/2 + .5, datac$N-1)
datac$ci <- datac$se * ciMult
return(datac)
}
#依據分組對vale進行統計
Data_summary <- summarySE(Data, measurevar="value", groupvars=c("Group","Attribute"))
P1 <- ggplot(Data, aes(x=Group, y=value,fill=Attribute)) +
stat_eye(aes(alpha = stat(f)), show_interval = FALSE, trim=FALSE, position=position_dodge(0.9)) + #alpha = stat(f)表示按照數據分佈密度選擇不同同透明度的顏色填充
geom_point(data = Data_summary,aes(x=Group, y=value),pch=19,position=position_dodge(0.9),size=1.5)+ #繪製均值爲點圖
geom_errorbar(data = Data_summary,aes(ymin = value-sd, ymax=value+sd), #誤差條表示均值±標準差
width=0.1, #誤差條末端短橫線的寬度
position=position_dodge(0.9),
color="black",
alpha = 0.7,
size=0.5) +
scale_fill_manual(values = c("#56B4E9", "#E69F00"))+ #設置填充的顏色
theme_classic()+
theme(legend.position="none") #不需要圖例
P1
jpeg(file = "results_Value_1.jpg",width =1600,height = 2000,units = "px",res =300) #結果保存
print(P1)
dev.off()
效果如如下:
分半的小提琴圖結合誤差條圖的代碼如下:
P2 <- ggplot(Data, aes(x=Group, y=value,fill=Attribute)) +
stat_halfeye(data = Data[Attribute == "Attribute_1",],aes(alpha = stat(f)), show_interval = FALSE, trim=FALSE,side = "left", width = 0.4) +
stat_halfeye(data = Data[Attribute == "Attribute_2",],aes(alpha = stat(f)), show_interval = FALSE, trim=FALSE,side = "right", width = 0.4) +
geom_point(data = Data_summary,aes(x=Group, y=value),pch=19,position=position_dodge(0.5),size=1.5)+ #繪製均值爲點圖
geom_errorbar(data = Data_summary,aes(ymin = value-sd, ymax=value+sd), #誤差條表示均值±標準差
width=0.1, #誤差條末端短橫線的寬度
position=position_dodge(0.5),
color="black",
alpha = 0.7,
size=0.5) +
scale_fill_manual(values = c("#56B4E9", "#E69F00"))+ #設置填充的顏色
theme_classic()+
theme(legend.position="none") #不需要圖例
P2
jpeg(file = "results_Value_2.jpg",width =1600,height = 2000,units = "px",res =300) #結果保存
print(P2)
dev.off()
效果圖如下:
繪製分半小提琴圖時,Attribute_1的數據採用左半邊顯示,Attribute_2的數據採用右半邊顯示,因此,繪製時分兩次繪製,但需要控制每次輸入的數據,如繪製左邊時,僅將Attribute == "Attribute_1"的數據作爲輸入。
tidybayes包提供了多種用於表示數據分佈的繪圖方式,包括:小提琴圖,分半小提琴圖,概率密度圖、直方圖等多種形式,還可以靈活設置垂直方向或水平方向顯示。示例圖如下所示。
tidybayes包的更多學習資料請參考:https://mjskay.github.io/tidybayes/articles/slabinterval.html
採用tidybayes包中的stat_ gradient interval()呈現數據的方式如下:
P3 <- ggplot(Data, aes(x=Group, y=value,fill=Attribute)) +
stat_gradientinterval(aes(alpha = stat(f)), show_interval = FALSE, trim=FALSE,position=position_dodge(0.5), width = 0.5) +
geom_point(data = Data_summary,aes(x=Group, y=value),pch=19,position=position_dodge(0.5),size=1.5)+ #繪製均值爲點圖
geom_errorbar(data = Data_summary,aes(ymin = value-sd, ymax=value+sd), #誤差條表示均值±標準差
width=0.1, #誤差條末端短橫線的寬度
position=position_dodge(0.5),
color="black",
alpha = 0.7,
size=0.5) +
scale_fill_manual(values = c("#56B4E9", "#E69F00"))+ #設置填充的顏色
theme_classic()+
theme(legend.position="none") #不需要圖例
P3
jpeg(file = "results_Value_3.jpg",width =1600,height = 2000,units = "px",res =300) #結果保存
print(P3)
dev.off()
效果圖如下:
References
- Slab + interval stats and geoms:https://mjskay.github.io/tidybayes/articles/slabinterval.html