在R语言中重现目标学术热图的配色方案
问题
我正在使用R语言开发,在一篇论文中发现了心仪的热图,想要尝试重现。参考教程模拟数据后编写了如下R代码:
library(ggplot2) library(reshape2) library(metR) set.seed(123) Biomass <- seq(0, 10, length.out = 100) variable <- seq(0, 10, length.out = 100) con <- data.frame(matrix(ncol = length(variable), nrow = length(Biomass))) for (i in 1:length(Biomass)) { for (j in 1:length(variable)) { con[i, j] <- sin(Biomass[i]) + cos(variable[j]) # adjust this as needed } } rownames(con) <- Biomass con <- cbind(Biomass = rownames(con), con) rownames(con) <- NULL con$Biomass <- as.numeric(con$Biomass) conm = melt(con, id = "Biomass") conm$variable <- gsub("X", "", conm$variable) conm$variable = as.numeric(conm$variable) gg = ggplot(conm, aes(x = variable, y = Biomass)) + geom_raster(aes(fill = value)) + geom_contour(aes(z = value), colour = "white", size = 0.2, alpha = 0.5) + geom_text_contour(aes(z = value), colour = "white" ) + labs(x = "Filtered light intensity (umol photons/m2/s)", y = "Dry Biomass Concentration (g/L)", fill = "Productivity (umol O2/g biomass/s)") + theme(legend.title = element_text(size = 10, face = "bold"), legend.position = "top", panel.background = element_blank(), axis.text = element_text(colour = "black", size = 10, face = "bold"), axis.title = element_text(size = 12, face = "bold"), legend.text = element_text(size = 11), legend.key = element_blank()) + scale_fill_continuous(low = "#BFE1B0", high = "#137177") + scale_y_continuous(expand = c(0,0)) + scale_x_continuous(expand = c(0,0)) gg
当前生成的热图:
请问是否可以重现目标热图的配色方案?
解决方案
当然可以重现目标热图的配色方案,以下是几种可行的实现方式:
1. 提取目标热图的颜色值
使用取色工具(比如系统自带取色器)从目标热图中提取关键渐变节点的十六进制色值,然后通过scale_fill_gradientn指定多色渐变,或替换scale_fill_continuous的low和high参数:
# 示例:假设提取的颜色为浅橙到深褐的渐变 scale_fill_gradientn(colors = c("#FFE8CC", "#FFB74D", "#E67E22", "#8E44AD"))
2. 使用专业配色包匹配风格
如果目标热图采用科研领域常用配色体系,可借助R配色包快速实现:
- 暖色调渐变(适配高对比度科研热图):
library(RColorBrewer) scale_fill_distiller(palette = "YlOrRd", direction = 1)
- 冷色调渐变(适配蓝绿系专业热图):
library(viridis) scale_fill_viridis(option = "mako")
3. 直接修改现有代码的配色
针对你当前的代码,只需替换scale_fill_continuous中的色值参数即可,将现有配色替换为目标热图的深浅色:
# 替换为从目标图提取的浅色调和深色调 scale_fill_continuous(low = "#你的浅色调十六进制值", high = "#你的深色调十六进制值")
内容的提问来源于stack exchange,提问作者stats_noob
相关产品推荐
相关产品推荐

