R中能绘制相关性热图的包有很多corrplot、corrgram、ggcorrplot等,这些R包都有丰富的功能,但是如果需要对图像进行自定义难免受到他人函数约束,下面介绍如何自定义准备ggplot2需要的相关性数据
下载并加载R包
package.list=c("tidyverse","lucid")
for (package in package.list) {
if (!require(package,character.only=T, quietly=T)) {
install.packages(package)
library(package, character.only=T)
}
}
定义函数
使用Hmisc::rcorr()函数来计算相关性
cors <- function(df) {
m <- Hmisc::rcorr(as.matrix(df))
mdf <- map(m, ~data.frame(.x))
return(mdf)
}
df_cor <- function(df){
cors(df) %>%
map(~rownames_to_column(.x, var="ID1")) %>%
map(~pivot_longer(.x, -ID1,"ID2")) %>%
bind_rows(.id = "id") %>%
pivot_wider(names_from = id, values_from = value) %>%
mutate(p_if = ifelse(P <.05, P, NA), # P <0.05 返回P值
r_if = ifelse(P <.05, r, NA), # p <0.05 返回r值
p_signif=symnum(P, corr = FALSE, na = FALSE,
cutpoints = c(0, 0.001, 0.01, 0.05, 0.1, 1),
symbols = c("***", "**", "*", ".", " "))) # 将P值转化为*
}
下面让我们测试一下函数(n表示用于每个相关性的观测值数量)
df_cor(mtcars)
ID1 ID2 r n P p_if r_if p_signif
1 mpg mpg 1 32 NA NA NA
2 mpg cyl -0.852 32 6.11e-10 6.11e-10 -0.852 ***
3 mpg disp -0.848 32 9.38e-10 9.38e-10 -0.848 ***
4 mpg hp -0.776 32 1.79e- 7 1.79e- 7 -0.776 ***
5 mpg drat 0.681 32 1.78e- 5 1.78e- 5 0.681 ***
数据可视化(1)
df_cor(mtcars) %>%
ggplot(aes(ID1,ID2,color=r)) +
geom_tile(col="black", fill="white") +
geom_point(aes(size = abs(r)),shape=15) +
geom_text(aes(label=p_signif),size=5,color="white",
hjust=0.5,vjust=0.7)+
labs(x = NULL, y = NULL)+
theme_classic() +
theme(axis.text=element_text(color="black"))+
scale_color_gradient2(mid="#FBFEF9",
low="#0C6291",high="#A63446") +
scale_x_discrete(expand=c(0,0)) +
scale_y_discrete(expand=c(0,0))+
scale_size(range=c(1,11), guide=NULL)
数据可视化(2)
df_cor(mtcars) %>%
ggplot(aes(ID1,ID2,fill=r,label=round(r_if,2))) +
geom_tile() +
labs(x = NULL,y=NULL) +
scale_fill_gradient2(mid="#FBFEF9",low="#0C6291",high="#A63446", limits=c(-1,1)) +
geom_text() +
theme_classic() +
scale_x_discrete(expand=c(0,0)) +
scale_y_discrete(expand=c(0,0))+
theme(axis.text=element_text(color="black"))
喜欢的小伙伴欢迎关注我的公众号 ,下回更新不迷路
R语言数据分析指南,持续分享数据可视化的经典案例及一些生信知识,希望对大家