如何让ggplot为0-10的11个空间数据值分配唯一渐变颜色?
解决ggplot中0-10数值仅显示10种颜色的问题
问题原因
使用scale_fill_stepsn时,默认会根据breaks划分区间:当breaks=seq(0,10,1)时,会生成10个连续区间(0-1、1-2……9-10),每个区间对应1种颜色,因此11个数值被映射到10种颜色中,无法显示11种唯一颜色。
解决方案
有两种可行的处理方式:
方法1:使用离散颜色映射(推荐,因为数据是整数离散值)
将layer转换为因子类型,用scale_fill_manual直接为每个离散值分配唯一颜色:
library(ggplot2) library(raster) # 生成颜色序列 cols <- colorRampPalette(c("yellow", "red", "darkred", "black")) # 创建栅格数据 r <- raster(ncol=100, nrow=100) r[] <- sample(0:10, 10000, replace = T) # 转换为数据框 r_df <- as.data.frame(r, xy=T) # ggplot绘图 ggplot(data = r_df) + geom_raster(aes(x = x, y = y, fill = factor(layer)), interpolate = F) + scale_fill_manual( values = cols(11), breaks = 0:10, labels = 0:10, name = "数值" ) + theme_minimal()
方法2:调整连续颜色映射的区间范围
通过设置limits扩展边界,让每个整数数值对应独立的区间(如-0.50.5对应0,0.51.5对应1……9.5~10.5对应10),这样11个数值对应11个区间,刚好匹配11种颜色:
ggplot(data = r_df) + geom_raster(aes(x = x, y = y, fill = layer), interpolate = F) + scale_fill_stepsn( colors = cols(11), breaks = 0:10, limits = c(-0.5, 10.5), # 扩展边界生成11个区间 show.limits = TRUE, name = "数值" ) + theme_minimal()
内容的提问来源于stack exchange,提问作者Ferdi
相关产品推荐
相关产品推荐

