在ggplot2中为不同图层设置不同调色板
问题描述
需要绘制动物在活动场地中的运动轨迹,同时展示场地热图与按移动速度颜色编码的轨迹。已通过stat_density2d生成了BuGn色系的背景热图,但叠加geom_path后,轨迹的速度颜色区分度不足。
示例数据:
set.seed(100) df <- data.frame(frame = seq(1,50,1), x = c(51.34564, 52.02254, 52.60115, 53.20906, 53.88028, 54.55151, 55.13741, 55.41307, 56.08957, 56.68501, 57.28044, 57.62111, 58.13888, 58.38356, 58.38356, 58.38356, 58.17859, 57.52251, 56.86643, 56.21035, 55.55427, 54.89819, 54.54640, 54.19461, 53.85371, 53.51281, 53.01192, 52.51103, 51.82817, 51.14532, 50.46246, 49.82272, 49.18298, 48.38321, 47.58344, 46.78368, 45.98391, 45.18414, 44.38437, 43.55679, 42.78776, 42.02832, 41.24797, 40.38921, 39.67093, 38.78841, 38.07554, 37.04552, 36.21359, 35.42233), y = c(93.59669, 93.82952, 94.02557, 94.15208, 94.44488, 94.73768, 95.12280, 95.37992, 95.68827, 95.97229, 96.25632, 96.38436, 96.71693, 96.98220, 97.23499, 97.48778, 97.84184, 98.40484, 98.96784, 99.53085, 100.09385, 100.65685, 101.04628, 101.43570, 101.85187, 102.26803, 102.85582, 103.44360, 104.01978, 104.59596, 105.17213, 105.76429, 106.35644, 106.09024, 105.82403, 105.55783, 105.29163, 105.02542, 104.75922, 104.44431, 104.13191, 103.54044, 103.15739, 102.96974, 102.55943, 101.98391, 101.39337, 101.03815, 100.69386, 100.23876), speed = runif(50, min=0, max=5)) # 修正原数据speed长度与frame不匹配的问题
尝试的代码:
ggplot(df, aes(x,y)) + xlab('X') + ylab('Y') + stat_density2d(aes(fill=after_stat(density)), contour=FALSE, geom="raster", data=df) + scale_fill_distiller(palette="BuGn", direction=-1) + geom_path(data=df, aes(x=x, y=y, color=speed), size=1) + theme_classic()
解决方案
要保留热图BuGn配色的同时提升轨迹速度颜色的区分度,只需为轨迹图层单独指定颜色刻度,以下是几种可行方案:
1. 使用Distiller内置渐变配色
选择与冷色调BuGn热图对比强烈的冷暖渐变配色,比如RdYlBu,通过scale_color_distiller设置:
ggplot(df, aes(x,y)) + xlab('X') + ylab('Y') + stat_density2d(aes(fill=after_stat(density)), contour=FALSE, geom="raster") + scale_fill_distiller(palette="BuGn", direction=-1) + geom_path(aes(color=speed), size=1) + # 为轨迹指定独立的颜色刻度,RdYlBu冷暖渐变与BuGn形成鲜明对比 scale_color_distiller(palette="RdYlBu", direction=1, name="Speed") + theme_classic()
2. 使用Brewer离散配色(速度分箱展示)
若希望将速度划分为多个区间展示,可配合cut()函数和scale_color_brewer的高饱和度配色:
ggplot(df, aes(x,y)) + xlab('X') + ylab('Y') + stat_density2d(aes(fill=after_stat(density)), contour=FALSE, geom="raster") + scale_fill_distiller(palette="BuGn", direction=-1) + # 将speed分为3个区间 geom_path(aes(color=cut(speed, breaks=3)), size=1) + # Set1高饱和度配色,在绿色热图上清晰突出不同速度区间 scale_color_brewer(palette="Set1", name="Speed Range") + theme_classic()
3. 自定义渐变配色
如果内置配色不符合需求,可通过scale_color_gradient创建完全自定义的渐变范围,确保与热图配色不冲突:
ggplot(df, aes(x,y)) + xlab('X') + ylab('Y') + stat_density2d(aes(fill=after_stat(density)), contour=FALSE, geom="raster") + scale_fill_distiller(palette="BuGn", direction=-1) + geom_path(aes(color=speed), size=1) + # 自定义从深蓝到深红的渐变,与绿色热图形成强烈对比 scale_color_gradient(low="darkblue", high="darkred", name="Speed") + theme_classic()
内容的提问来源于stack exchange,提问作者alyb_batgirl
相关产品推荐
相关产品推荐

