【R语言】随机森林+相关性热图组合图

devtools/2024/10/21 13:40:57/

数据概况文末有获取方式

随机森林部分

#调用R包
library(randomForest)
library(rfPermute)
library(ggplot2)
library(psych)
library(reshape2)
library(patchwork)
library(reshape2)
library(RColorBrewer)
​
​
#读取数据
df<-read.csv("F:\\EXCEL-元数据\\2020中.csv")
​
#设置随机种子,使结果能够重现
set.seed(123)
​
#运行随机森林
rf_results<-rfPermute(ESI~., data =df, importance = TRUE, ntree = 500)
​#查看随机森林主要结果
rf_results$rf
​
#提取预测因子的解释率
predictor_var<- data.frame(importance(rf_results, scale = TRUE), check.names = FALSE)
​
#提取预测变量的显著
predictor_sig<-as.data.frame((rf_results$pval)[,,2])
colnames(predictor_sig)<-c("sig","other")
​
#合并显著因子和解释率表
df_pre<-cbind(predictor_var,predictor_sig)
df_pre$sig[df_pre$sig<=0.05]<-"*"
df_pre$sig[df_pre$sig>=0.05]<-" "
k <- df_pre$IncNodePurity[df_pre$sig=="*"]<-"#99c1e1"
​
# 自定义顺序列表
custom_order <- c("TEM", "PRE", "NDVI", "DEM", "SLOPE","LANDUSE","NPP","POP","GDP")
# 创建行名列
df_pre$rowname <- factor(rownames(df_pre), levels = custom_order)

绘制随机森林条形图

# 绘制柱状图,使用自定义顺序
p1 <- ggplot(data=df_pre, aes(x=`%IncMSE`, y=rowname)) +geom_bar(stat='identity', width=0.6,fill=k) +#geom_errorbar(aes(xmin=mean-sd, xmax=mean+sd), width = 0.2, color = "black") +theme_classic() + labs(x='Increase in MSE(%)', y='') +scale_x_continuous(limits = c(min(0), max(df_pre$`%IncMSE`) + 10),breaks=seq(0,max(df_pre$`%IncMSE`) + 10,20),expand = c(0, 0)) +geom_text(aes(label=sig, x=`%IncMSE` + 0.1, y=rowname), hjust=-0.3, size=6) +theme(axis.text.y = element_blank())+theme(axis.text=element_text(color="black", size=11),axis.ticks.y = element_blank(),panel.grid.major.y = element_blank(),panel.grid.minor.y = element_blank(),panel.border = element_blank(),panel.background = element_blank())
p1

结果如下:

相关性热图部分

#读取环境变量和影响因子矩阵
env <- df$ESI
spe <- df[,-1]
#spe <- spe[rownames(env), ]
####环境变量和影响因子的相关性分析
library(psych)
library(reshape2)
#可通过 psych 包函数 corr.test() 执行
#这里以 pearson 相关系数为例,暂且没对 p 值进行任何校正(可以通过 adjust 参数额外指定 p 值校正方法)
pearson <- corr.test(env, spe, method = 'pearson', adjust = 'none')
r <- data.frame(pearson$r)  #pearson 相关系数矩阵
p <- data.frame(pearson$p)  #p 值矩阵
#结果整理以便于作图
r$env <- rownames(r)
p$env <- rownames(p)
r <- melt(r, id = 'env')
p <- melt(p, id = 'env')
pearson <- cbind(r, p$value)
colnames(pearson) <- c('env', 'spe', 'pearson_correlation', 'p.value')
pearson$spe <- factor(pearson$spe, levels = colnames(spe))
head(pearson)  
​
#ggplot2 作图,绘制环境变量和因子的 pearson 相关性热图
​
# 自定义顺序列表
custom_order <- c("TEM", "PRE", "NDVI", "DEM", "SLOPE","LANDUSE","NPP","POP","GDP")
​
# 将 'env' 列转换为因子,并按照自定义顺序排序
pearson$env <- factor(pearson$env, levels = custom_order)

出图

# 使用排序后的数据绘制热图
p2 <- ggplot() +geom_tile(data = pearson, aes(x = env, y = spe, fill = pearson_correlation)) +scale_fill_gradientn(colors = c('#3e689d', '#e8f0db', '#b0271f'), limit = c(-1, 1)) +theme(panel.grid = element_line(), panel.background = element_rect(color = 'black'), legend.key = element_blank(), legend.position = "bottom",#legend.margin = margin(t = -1, unit = "cm"),  # 调整图例和图的上方间距#legend.box.margin = margin(t = 0, unit = "cm"),  # 调整图例内部内容的上方间距axis.text.x = element_text(color = 'black', angle = 45, hjust = 1, vjust = 1), axis.text.y = element_text(color = 'black',size=12), axis.ticks = element_line(color = 'black')) +scale_x_discrete(expand = c(0, 0)) +scale_y_discrete(expand = c(0, 0)) +coord_fixed(ratio=1) +theme(axis.text.x = element_blank(),axis.ticks.x = element_blank(),panel.grid.major.x = element_blank(),panel.grid.minor.x = element_blank(),panel.border = element_blank(),panel.background = element_blank())+labs(y = '', x = '', fill = '')
​
p2
​
#如果想把 pearson 相关系数的显著性也标记在图中,参考如下操作
pearson[which(pearson$p.value<0.001),'sig'] <- '***'
pearson[which(pearson$p.value<0.01 & pearson$p.value>0.001),'sig'] <- '**'
pearson[which(pearson$p.value<0.05 & pearson$p.value>0.01),'sig'] <- '*'
head(pearson)  #整理好的环境变量和物种丰度的 pearson 相关性统计表
​
p3 <- p2 +geom_text(data = pearson, aes(x = env, y = spe, label = sig), size = 6)
​
p3

合并两幅图,并导出

p3<-p3+theme(plot.margin = margin(0,0,0,0))  # 分别为上、右、下、左
p1<-p1+theme(plot.margin = margin(0,0,0,0))
​
p3+p1
​
#保存至ppt
library(eoffice)
topptx(filename = "F:\\出图\\2020中.pptx",height=5,width=3)

完整代码

#下载r包
install.packages("rfPermute")
install.packages("ggplot2")
install.packages("psych")
install.packages("reshape2")
install.packages("patchwork")
install.packages("randomForest")
​
#调用R包
library(randomForest)
library(rfPermute)
library(ggplot2)
library(psych)
library(reshape2)
library(patchwork)
library(reshape2)
library(RColorBrewer)
​
​
#读取数据
df<-read.csv("F:\\EXCEL-元数据\\2020中.csv")
​
#设置随机种子,使结果能够重现
set.seed(123)
​
#运行随机森林
rf_results<-rfPermute(ESI~., data =df, importance = TRUE, ntree = 500)
​#查看随机森林主要结果
rf_results$rf
​
#提取预测因子的解释率
predictor_var<- data.frame(importance(rf_results, scale = TRUE), check.names = FALSE)
​
#提取预测变量的显著
predictor_sig<-as.data.frame((rf_results$pval)[,,2])
colnames(predictor_sig)<-c("sig","other")
​
#合并显著因子和解释率表
df_pre<-cbind(predictor_var,predictor_sig)
df_pre$sig[df_pre$sig<=0.05]<-"*"
df_pre$sig[df_pre$sig>=0.05]<-" "
k <- df_pre$IncNodePurity[df_pre$sig=="*"]<-"#99c1e1"
​
# 自定义顺序列表
custom_order <- c("TEM", "PRE", "NDVI", "DEM", "SLOPE","LANDUSE","NPP","POP","GDP")
# 创建行名列
df_pre$rowname <- factor(rownames(df_pre), levels = custom_order)
​
​
​
# 绘制柱状图,使用自定义顺序
p1 <- ggplot(data=df_pre, aes(x=`%IncMSE`, y=rowname)) +geom_bar(stat='identity', width=0.6,fill=k) +#geom_errorbar(aes(xmin=mean-sd, xmax=mean+sd), width = 0.2, color = "black") +theme_classic() + labs(x='Increase in MSE(%)', y='') +scale_x_continuous(limits = c(min(0), max(df_pre$`%IncMSE`) + 10),breaks=seq(0,max(df_pre$`%IncMSE`) + 10,20),expand = c(0, 0)) +geom_text(aes(label=sig, x=`%IncMSE` + 0.1, y=rowname), hjust=-0.3, size=6) +theme(axis.text.y = element_blank())+theme(axis.text=element_text(color="black", size=11),axis.ticks.y = element_blank(),panel.grid.major.y = element_blank(),panel.grid.minor.y = element_blank(),panel.border = element_blank(),panel.background = element_blank())
p1
​
​
#读取环境变量和物种丰度矩阵
env <- df$ESI
spe <- df[,-1]
#spe <- spe[rownames(env), ]
####环境变量和物种丰度的相关性分析
library(psych)
library(reshape2)
#可通过 psych 包函数 corr.test() 执行
#这里以 pearson 相关系数为例,暂且没对 p 值进行任何校正(可以通过 adjust 参数额外指定 p 值校正方法)
pearson <- corr.test(env, spe, method = 'pearson', adjust = 'none')
r <- data.frame(pearson$r)  #pearson 相关系数矩阵
p <- data.frame(pearson$p)  #p 值矩阵
#结果整理以便于作图
r$env <- rownames(r)
p$env <- rownames(p)
r <- melt(r, id = 'env')
p <- melt(p, id = 'env')
pearson <- cbind(r, p$value)
colnames(pearson) <- c('env', 'spe', 'pearson_correlation', 'p.value')
pearson$spe <- factor(pearson$spe, levels = colnames(spe))
head(pearson)  #整理好的环境变量和物种丰度的 pearson 相关性统计表
​
#ggplot2 作图,绘制环境变量和物种丰度的 pearson 相关性热图
​
# 自定义顺序列表
custom_order <- c("TEM", "PRE", "NDVI", "DEM", "SLOPE","LANDUSE","NPP","POP","GDP")
​
# 将 'env' 列转换为因子,并按照自定义顺序排序
pearson$env <- factor(pearson$env, levels = custom_order)
​
# 使用排序后的数据绘制热图
p2 <- ggplot() +geom_tile(data = pearson, aes(x = env, y = spe, fill = pearson_correlation)) +scale_fill_gradientn(colors = c('#3e689d', '#e8f0db', '#b0271f'), limit = c(-1, 1)) +theme(panel.grid = element_line(), panel.background = element_rect(color = 'black'), legend.key = element_blank(), legend.position = "bottom",#legend.margin = margin(t = -1, unit = "cm"),  # 调整图例和图的上方间距#legend.box.margin = margin(t = 0, unit = "cm"),  # 调整图例内部内容的上方间距axis.text.x = element_text(color = 'black', angle = 45, hjust = 1, vjust = 1), axis.text.y = element_text(color = 'black',size=12), axis.ticks = element_line(color = 'black')) +scale_x_discrete(expand = c(0, 0)) +scale_y_discrete(expand = c(0, 0)) +coord_fixed(ratio=1) +theme(axis.text.x = element_blank(),axis.ticks.x = element_blank(),panel.grid.major.x = element_blank(),panel.grid.minor.x = element_blank(),panel.border = element_blank(),panel.background = element_blank())+labs(y = '', x = '', fill = '')
​
p2
​
#如果想把 pearson 相关系数的显著性也标记在图中,参考如下操作
pearson[which(pearson$p.value<0.001),'sig'] <- '***'
pearson[which(pearson$p.value<0.01 & pearson$p.value>0.001),'sig'] <- '**'
pearson[which(pearson$p.value<0.05 & pearson$p.value>0.01),'sig'] <- '*'
head(pearson)  #整理好的环境变量和物种丰度的 pearson 相关性统计表
​
p3 <- p2 +geom_text(data = pearson, aes(x = env, y = spe, label = sig), size = 6)
​
p3
​
​
p3<-p3+theme(plot.margin = margin(0,0,0,0))  # 分别为上、右、下、左
p1<-p1+theme(plot.margin = margin(0,0,0,0))
​
p3+p1
​
#保存至ppt
library(eoffice)
topptx(filename = "F:\\出图\\2020中.pptx",height=5,width=3)


http://www.ppmy.cn/devtools/125581.html

相关文章

人工智能和机器学习之线性代数(一)

人工智能和机器学习之线性代数&#xff08;一&#xff09; 人工智能和机器学习之线性代数一将介绍向量和矩阵的基础知识以及开源的机器学习框架PyTorch。 文章目录 人工智能和机器学习之线性代数&#xff08;一&#xff09;基本定义标量&#xff08;Scalar&#xff09;向量&a…

Ubuntu 18.04安装storcli查看阵列信息

rootCeph03:/opt/MegaRAID/storcli# cat /etc/issue Ubuntu 18.04.5 LTS \n \l 准备好storcli的安装包 解压 解压之后可以看到 根据系统版本选择 把storcli_1.18.11_all.deb包传到服务器 使用命令dpkg -I storcli_1.18.11_all.deb ./storcli64 show ./storcli64 /c1 show …

2.随机变量及其分布

第二章 随机变量及其分布 1. 随机变量及其分布 1.1 随机变量的定义 定义1.1 随机变量 ​ 定义在样本空间 Ω \Omega Ω上的实值函数 X X ( ω ) XX(\omega) XX(ω)称为随机变量,常用大写字母 X , Y , Z X,Y,Z X,Y,Z等表示随机变量&#xff0c;其取值用小写字母 x , y , z …

智汇云舟亮相WAFI世界农业科技创新大会,并参编数字农业产业图谱

10月10日&#xff0c;2024WAFI世界农业科技创新大会农食行业创新与投资峰会在北京金海湖国际会展中心举行。中国农业大学MBA教育中心主任、教授付文阁、平谷区委常委、统战部部长刘堃、华为公共事业军团数字政府首席专家刘丹、荷兰瓦赫宁根大学前校长Aalt Dijkhuizen、牧原食品…

通过API获取Milvus实例详情

GetInstanceDetail - 获取实例详情 获取单个实例的详细信息。 调试 您可以在OpenAPI Explorer中直接运行该接口&#xff0c;免去您计算签名的困扰。运行成功后&#xff0c;OpenAPI Explorer可以自动生成SDK代码示例。 ​编辑调试 授权信息 下表是API对应的授权信息&#…

Fiddler配合wireshark解密ssl

环境&#xff1a; win11&#xff08;wireshark&#xff09;--虚拟机win7&#xff08;Fiddler&#xff09;---虚拟机win7&#xff08;HTTPS站点&#xff09; 软件安装问题&#xff1a; 需要.net环境&#xff0c;NDP461-KB3102436-x86-x64-AllOS-ENU.exe。 安装fiddler后安装下…

神经网络模型的“扩散与进化”思想启迪

在上一篇笔记「上交大全华班复现o1旅程式学习下的深思考」中&#xff0c;其中对于上交大提出的旅程学习即system2慢思考认知范式下对于“多步骤的隐式到显式空间状态映射下的细粒度联合概率分布建模”的描述隐喻为“社会心理学或社会经济学两种不同的长程动态系统慢演化现象”。…

HCIP-HarmonyOS Application Developer 习题(九)

(多选) 1、HarmonyOS多窗口交互能力提供了以下哪几种交互方式&#xff1f; A. 全局消息通知 B.平行视界 C.悬浮窗 D.分屏 答案&#xff1a;BCD 分析&#xff1a;系统提供了悬浮窗、分屏、平行视界三种多窗口交互&#xff0c;为用户在大屏幕设备上的多任务并行、便捷的临时任务…